为材质 UI 范围滑块的拇指设置不同的颜色

时间:2021-03-17 03:41:51

标签: css reactjs material-ui slider rangeslider

嗨,我正在使用 Material UI 滑块组件构建一个具有 2 个值的范围滑块,并且我正在尝试使两个拇指具有不同的颜色。

enter image description here

我该怎么做?

1 个答案:

答案 0 :(得分:3)

这有点笨拙,但它可以实现您的愿望。

本质上,您希望利用 MaterialUI 的 useStyle 创建自定义样式,然后通过引用其子索引来选择拇指元素。

因为可以预见拇指是范围滑块中的第 4 个和第 5 个元素,您可以使用一些 CSS 选择它们并相应地设置它们的样式:

enter image description here

import React from "react";
import { Slider, Typography } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";

export default function StyledSlider() {
  const [value, setValue] = React.useState([20, 37]);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  const useStyles = makeStyles({
    root: {
      "&>.MuiSlider-thumb": {
        "&:nth-child(4)": {
          color: "green !important"
        },
        "&:nth-child(5)": {
          color: "red !important"
        }
      }
    }
  });

  const classes = useStyles();

  return (
    <div>
      <Typography id="range-slider" gutterBottom>
        Example Slider
      </Typography>
      <Slider
        value={value}
        onChange={handleChange}
        valueLabelDisplay="auto"
        aria-labelledby="range-slider"
        className={classes.root}
      />
    </div>
  );
}

工作代码沙盒:https://codesandbox.io/s/stack-66666691-muithumbs-4s3rh?file=/src/StyledSlider.jsx:0-900

参考文献: