禁用后如何更改Material-UI滑块的拇指样式

时间:2020-04-14 11:26:39

标签: javascript html css reactjs material-ui

我可以使用Slider来修改withStyles样式:

const CustomSlider = withStyles(theme => ({
  disabled: {
    color: theme.palette.primary.main
  },
  thumb: {
    height: 24,
    width: 24,
  },
}))(Slider);

但是仅当组件为height时才应用拇指的widthdisabled={false}

是否有一种简单的方法来更改height上的滑块widthdisabled={true}

演示: https://codesandbox.io/s/slide-thumb-size-gxb4g?file=/demo.js

1 个答案:

答案 0 :(得分:2)

原因

样式已由className Mui-disabled

覆盖

您可以看到颜色保持不变。

enter image description here

如何解决

覆盖MuiSlider-thumbMui-disabled的样式

一个选项:使用MUI className nesting selector

"& .MuiSlider-thumb": {
  height: 24,
  width: 24
}

注意withStyles属性是指CSS API,您可以使用className +样式钩子来自定义CSSAPI不会公开的className

完整代码:

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

const useStyles = makeStyles(theme => ({
  margin: {
    margin: theme.spacing(10),
    "& .MuiSlider-thumb": {
      height: 24,
      width: 24
    }
  }
}));

const CustomSlider = withStyles(theme => ({
  disabled: {
    color: theme.palette.primary.main
  },
  thumb: {
    // color: "red"
  }
}))(Slider);

export default function MyCustomSlider() {
  const classes = useStyles();
  return (
    <div>
      <Paper className={classes.margin}>
        <CustomSlider
          defaultValue={[10, 15]}
          min={0}
          max={20}
          valueLabelDisplay="on"
          disabled={true}
        />{" "}
        <CustomSlider
          defaultValue={[5, 7]}
          min={0}
          max={20}
          valueLabelDisplay="on"
          disabled={false}
        />{" "}
      </Paper>
    </div>
  );
}

enter image description here


更新

对于withStyles

const styles = theme =>
  createStyles({
    margin: {
      margin: theme.spacing(10)
    },
    thumb: {
      "& .MuiSlider-thumb": {
        height: 24,
        width: 24
      }
    }
  });

function MyCustomSlider(props) {
  // const classes = useStyles();
  return (
    <div>
      <Paper className={props.classes.margin}>
        <Slider
          defaultValue={[10, 15]}
          min={0}
          max={20}
          valueLabelDisplay="on"
          disabled={true}
          className={props.classes.thumb}
        />{" "}
        <Slider
          defaultValue={[5, 7]}
          min={0}
          max={20}
          valueLabelDisplay="on"
          disabled={false}
        />{" "}
      </Paper>
    </div>
  );
}

export default withStyles(styles)(MyCustomSlider);

Edit Slide thumb size