How to overload material Switch component css

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-05 08:15:46

问题


I am trying to overload the MuiSwitch-track class of switch but it's not working.Basically i want to overload for a particular switch. I tried using

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

but it overloaded all switches. Is there any way to do the same for a single switch.

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

回答1:


Below is an example showing how to customize the track color for a Switch. This is based on the approach used for the default styles.

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>
  );
}



来源:https://stackoverflow.com/questions/60726466/how-to-overload-material-switch-component-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!