Switch 默认使用辅助颜色.
然后将拇指的颜色控制在colorSecondary
CSS。这里有默认样式对于该类:
/* Styles applied to the internal SwitchBase component's root element if `color="secondary"`. */
colorSecondary: {
'&$checked': {
color: theme.palette.secondary.main,
'&:hover': {
backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
'@media (hover: none)': {
backgroundColor: 'transparent',
},
},
},
'&$disabled': {
color: theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[800],
},
'&$checked + $track': {
backgroundColor: theme.palette.secondary.main,
},
'&$disabled + $track': {
backgroundColor:
theme.palette.type === 'light' ? theme.palette.common.black : theme.palette.common.white,
},
},
您可以使用以下内容调整主题中选中的颜色(显示覆盖拇指和轨道):
const theme = createMuiTheme({
overrides: {
MuiSwitch: {
switchBase: {
// Controls default (unchecked) color for the thumb
color: "#ccc"
},
colorSecondary: {
"&$checked": {
// Controls checked color for the thumb
color: "#f2ff00"
}
},
track: {
// Controls default (unchecked) color for the track
opacity: 0.2,
backgroundColor: "#fff",
"$checked$checked + &": {
// Controls checked color for the track
opacity: 0.7,
backgroundColor: "#fff"
}
}
}
}
});
对于 MUI v5
对于 v5,传递给的对象的结构createTheme
改变了。另一个变化是primary
现在是默认颜色而不是secondary
, 所以colorPrimary
样式需要被覆盖而不是colorSecondary
.
这是 v5 的等效代码:
import React from "react";
import FormGroup from "@mui/material/FormGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import Switch from "@mui/material/Switch";
import { createTheme, ThemeProvider } from "@mui/material/styles";
export default function CustomizedSwitches() {
const [state, setState] = React.useState({
checkedA: true
});
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setState({ ...state, [event.target.name]: event.target.checked });
};
const theme = createTheme({
components: {
MuiSwitch: {
styleOverrides: {
switchBase: {
// Controls default (unchecked) color for the thumb
color: "#ccc"
},
colorPrimary: {
"&.Mui-checked": {
// Controls checked color for the thumb
color: "#f2ff00"
}
},
track: {
// Controls default (unchecked) color for the track
opacity: 0.2,
backgroundColor: "#fff",
".Mui-checked.Mui-checked + &": {
// Controls checked color for the track
opacity: 0.7,
backgroundColor: "#fff"
}
}
}
}
}
});
return (
<ThemeProvider theme={theme}>
<FormGroup>
<FormControlLabel
control={
<Switch
checked={state.checkedA}
onChange={handleChange}
name="checkedA"
/>
}
label="Custom color"
/>
</FormGroup>
</ThemeProvider>
);
}