选中后,如何正确使用主题替代来覆盖MUISwitch的“条形”颜色?

时间:2019-05-02 09:04:25

标签: material-ui

仔细阅读source code之后,我尝试了以下方法,该方法可以工作,但会在控制台中生成警告。

const myTheme = createMuiTheme({
  overrides: {
    MuiSwitch: {
      checked: {
        "& + $bar": {
          opacity: 1.0,
          backgroundColor: "rgb(129, 171, 134)" // Light green, aka #74d77f
        }
      }
    }
  }
});

我得到的错误/警告是:

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

我不知道该怎么做。

更新:

我在下面有一个很好的解决方案,但是我的代码也覆盖了第二种颜色,而第二种颜色也被覆盖了。

colorSecondary: {
        "&$checked": {
          "& + $bar": {
            opacity: 0.3,
            backgroundColor: "white"
          }
        }
`

1 个答案:

答案 0 :(得分:1)

以下语法有效:

const theme = createMuiTheme({
  overrides: {
    MuiSwitch: {
      bar: {
        "$checked$checked + &": {
          opacity: 1.0,
          backgroundColor: "rgb(129, 171, 134)" // Light green, aka #74d77f
        }
      }
    }
  }
});

$checked在其中两次是为了增加特异性以匹配默认样式的特异性。

Edit Switch bar color

如果需要以不同方式处理三种不同的颜色选择,则可以执行以下操作:

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: {
      bar: {
        "$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);

Edit Switch bar color