问题
After perusing the source code I've tried the following, which works but generates a warning in the console.
const myTheme = createMuiTheme({
overrides: {
MuiSwitch: {
checked: {
"& + $bar": {
opacity: 1.0,
backgroundColor: "rgb(129, 171, 134)" // Light green, aka #74d77f
}
}
}
}
});
The error/warning I get is:
Warning: Material-UI: the `MuiSwitch` component increases the CSS specificity of the `checked` internal state.
You can not override it like this:
{
"checked": {
"& + $bar": {
"opacity": 1,
"backgroundColor": "rgb(129, 171, 134)"
}
}
}
Instead, you need to use the $ruleName syntax:
{
"&$checked": {
"& + $bar": {
"opacity": 1,
"backgroundColor": "rgb(129, 171, 134)"
}
}
}
I can't figure out how to do this properly.
Update:
I got a fine solution below but my code also has an overwrite of the secondary color which is different, and the new rule overwrites that one as well.
colorSecondary: {
"&$checked": {
"& + $bar": {
opacity: 0.3,
backgroundColor: "white"
}
}
`
回答1:
UPDATE - The original question was for v3 of Material-UI. In v4, the "bar" CSS class was renamed to "track". The examples in the answer have been updated for v4.
The following syntax works:
const theme = createMuiTheme({
overrides: {
MuiSwitch: {
track: {
"$checked$checked + &": {
opacity: 1.0,
backgroundColor: "rgb(129, 171, 134)" // Light green, aka #74d77f
}
}
}
}
});
$checked
is in there twice in order to increase the specificity to match the specificity of the default styling.
If you need to handle the three different color choices differently, then you can do something like the following:
import React from "react";
import ReactDOM from "react-dom";
import Switch from "@material-ui/core/Switch";
import { createMuiTheme, MuiThemeProvider } from "@material-ui/core/styles";
const theme = createMuiTheme({
overrides: {
MuiSwitch: {
track: {
"$checked:not($colorPrimary):not($colorSecondary) + &": {
opacity: 1.0,
backgroundColor: "rgb(129, 171, 134)"
},
"$checked$colorPrimary + &": {
opacity: 1.0,
backgroundColor: "purple"
},
"$checked$colorSecondary + &": {
opacity: 1.0,
backgroundColor: "pink"
}
}
}
}
});
function App() {
return (
<MuiThemeProvider theme={theme}>
<Switch color="default" />
<Switch color="primary" />
<Switch color="secondary" />
</MuiThemeProvider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
来源:https://stackoverflow.com/questions/55948999/how-do-i-properly-use-theme-overrides-for-the-muiswitch-bar-color-when-checked