【问题标题】:Setting different color for material UI range slider's thumbs为材质 UI 范围滑块的拇指设置不同的颜色
【发布时间】:2021-06-14 09:55:32
【问题描述】:

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

我该怎么做?

【问题讨论】:

    标签: css reactjs material-ui slider rangeslider


    【解决方案1】:

    这有点hacky,但它完成了你想要的。

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

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

    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

    参考资料:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多