如何重载材质切换组件css

IT技术 reactjs material-ui
2021-05-06 02:53:10

我试图重载 MuiSwitch-track 类的开关,但它不起作用。基本上我想重载特定的开关。我尝试使用

"@global": {
    ".MuiSwitch-track": {
      backgroundColor: "#d80c0a"
    }

但它使所有开关过载。有没有办法对单个开关做同样的事情。

 <Switch
                style={
                  this.state.switchChecked
                    ? { color: "rgb(65, 207, 65)" }
                    : { color: "#d80c0a" }
                }
                size="small"
                checked={switchChecked}
                onClick={this.handleSwitchState}
                value="userSwitch"
              />
1个回答

下面是一个示例,展示了如何自定义 Switch 的轨道颜色。这是基于用于默认样式的方法

import React from "react";
import Switch from "@material-ui/core/Switch";
import { withStyles } from "@material-ui/core/styles";

const CustomSwitch = withStyles({
  colorSecondary: {
    "&.Mui-checked + .MuiSwitch-track": {
      backgroundColor: "purple"
    }
  },
  track: {
    backgroundColor: "blue"
  }
})(Switch);

export default function Switches() {
  const [state, setState] = React.useState({
    checkedA: true,
    checkedB: true
  });

  const handleChange = name => event => {
    setState({ ...state, [name]: event.target.checked });
  };

  return (
    <div>
      <Switch
        checked={state.checkedA}
        onChange={handleChange("checkedA")}
        value="checkedA"
        inputProps={{ "aria-label": "secondary checkbox" }}
      />
      <CustomSwitch
        checked={state.checkedA}
        onChange={handleChange("checkedA")}
        value="checkedA"
        inputProps={{ "aria-label": "secondary checkbox" }}
      />
    </div>
  );
}

编辑自定义开关