【问题标题】:Material-UI - Thumbs switching style in range SliderMaterial-UI - 范围滑块中的拇指切换样式
【发布时间】:2021-10-06 23:51:12
【问题描述】:

我有两个实体要在 Material-UI Slider 上显示为拇指组件,我需要为每个拇指组件设置不同的样式。

实体 A 拇指应该出现在白色圆圈中,而实体 B 拇指应该出现在红色圆圈中。我通过使用数据索引部分实现了这个功能

if (data-index === 0) {

//show white circle
} else {
//show red circle
}

但是,这有一个很大的缺陷,即如果我滑动实体 B 并使其站在实体 A 之前,那么实体 B 会变为白色圆圈,因为实体 B 的数据索引变为 0。除了使用数据之外,还有其他方法吗?索引,无论它们在滑块上的位置如何,我都可以保持样式。

Here 是沙盒。

import * as React from "react";
import PropTypes from "prop-types";
import Slider, { SliderThumb } from "@material-ui/core/Slider";
import { styled } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";
import clsx from "clsx";

const EntitySlider = styled(Slider)(({ theme }) => ({
  color: "#3a8589",
  height: 3,
  padding: "13px 0",
  "& .MuiSlider-thumb": {
    height: 27,
    width: 27,
    backgroundColor: "#fff",
    border: "1px solid currentColor",
    "&.second-thumb": {
      backgroundColor: "red"
    },
    "&:hover": {
      boxShadow: "0 0 0 8px rgba(58, 133, 137, 0.16)"
    }
  },
  "& .MuiSlider-track": {
    height: 3
  },
  "& .MuiSlider-rail": {
    color: theme.palette.mode === "dark" ? "#bfbfbf" : "#d8d8d8",
    opacity: theme.palette.mode === "dark" ? undefined : 1,
    height: 3
  }
}));

function ThumbComponent(props) {
  const { children, className, ...other } = props;
  const extraClassName =
    other["data-index"] === 0 ? "first-thumb" : "second-thumb";
  return (
    <SliderThumb {...other} className={clsx(className, extraClassName)}>
      {children}
    </SliderThumb>
  );
}

ThumbComponent.propTypes = {
  children: PropTypes.node
};

export default function CustomizedSlider() {
  return (
    <Box sx={{ width: 320 }}>
      <Typography gutterBottom>Airbnb</Typography>
      <EntitySlider
        components={{ Thumb: ThumbComponent }}
        getAriaLabel={(index) =>
          index === 0 ? "Minimum price" : "Maximum price"
        }
        defaultValue={[20, 40]}
      />
    </Box>
  );
}

【问题讨论】:

    标签: javascript html css reactjs material-ui


    【解决方案1】:

    除了使用数据索引之外,还有其他方法可以保持样式,而不管它们在滑块上的位置

    您的样式按预期工作,唯一出乎意料的是,当您拖动白色拇指通过红色拇指时,红色拇指开始被拖动而白色拇指停止,因为 MUI Slider 不允许左拇指移动通过右手拇指。从源码中可以看到value数组总是得到sorted,而Sliderfind the closestthumb index从当前值设置为active:

    {/* white thumb on the left, red thumb on the right */}
    <Slider value={[0, 100]} {...} />
    {/* white thumb still on the left, red thumb still on the right */}
    <Slider value={[100, 0]} {...} />
    

    所以是的,拇​​指的样式是一致的,只是拇指位置被限制在其他拇指和最小值/最大值之间。

    参考

    【讨论】: