您可以使用 css/scss 覆盖 Material UI 中的样式吗?

rou*_*cle 5 sass reactjs material-ui next.js jss

目前我正在使用 SCSS,因为它很容易与 NextJS 一起使用。我真的很喜欢这个系统的工作方式,使用 SCSS 模块,所以我也想在使用 Material-UI 时使用它。Material-UI 使用 JSS,每次都要编写很多样板文件。此外,我不喜欢使用两种样式方式(SCSS 模块和 JSS)。我已经更改了 CSS 注入的顺序,以便我可以在 Material-UI 组件上使用我的 SCSS 模块。但是,我想知道是否有一种方法可以使用 SCSS 模块覆盖 Material-UI 组件的样式?我尝试过以下方法和一些类似的方法,但似乎没有任何效果:

import styles from "./Login.module.scss";

import Button from "@material-ui/core/Button";

function Login() {
  return (
    <section>
        <Button className={styles.button} variant="contained" color="primary">
          Verify
        </Button>
    </section>
  );
}

export default Login;
Run Code Online (Sandbox Code Playgroud)
.button {
  padding: 10px;
  margin-bottom: 10px;
  .MuiButton-containedPrimary {
    border: 2px solid red;
    background-color: red;
  }
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*ell 9

下面是正确的语法:

.button {
  padding: 10px;
  margin-bottom: 10px;
  &:global(.MuiButton-containedPrimary) {
    border: 2px solid red;
    background-color: red;
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑 SCSS 模块

上面的例子有两个关键的变化:

  1. 使用:global(.MuiButton-containedPrimary)。如果不使用:global,CSS 模块会将 转换MuiButton-containedPrimary为该模块特有的类名,然后它将与 Material-UI 在按钮上放置的内容不匹配。

  2. &在前面添加有效地创建了一个选择器,就像.button.MuiButton-containedPrimary将一个元素与其上的两个类相匹配一样。您的原始语法将被视为.MuiButton-containedPrimary后代选择器,并且仅与作为按钮后代的该类的元素匹配,而不是与按钮本身匹配。