Material UI 嵌套主题提供程序打破了 withStyles HOC

Who*_*eon 4 reactjs material-ui

我有一个使用 Create React App 创建的 React 应用程序,并使用 @material-ui/core npm 包进行主题化。

为了自定义组件,我使用 MaterialUI 提供的 withStyles 高阶组件。

根据文档,它支持嵌套 ThemeProviders https://material-ui.com/customization/theming/#nesting-the-theme

但在子 ThemeProvider withStyles 内部不会应用类。

这是一个演示该问题的基本应用程序 - > https://codesandbox.io/s/vibrant-tree-eh83d

示例组件.tsx

import React, { FunctionComponent } from "react";
import {
  WithStyles,
  withStyles,
  createStyles,
  StepButton,
  Step,
  Stepper,
  Box
} from "@material-ui/core";

const styles = createStyles({
  button: {
    "& .MuiStepIcon-root.MuiStepIcon-active": {
      fill: "red"
    }
  }
});

interface Props extends WithStyles<typeof styles> {
  title: string;
}

const ExampleComponent: FunctionComponent<Props> = ({ title, classes }) => {
  console.log(title, classes);
  return (
    <Box display="flex" alignItems="center">
      <span>{title}</span>
      <Stepper activeStep={0}>
        <Step>
          <StepButton className={classes.button}>Test</StepButton>;
        </Step>
      </Stepper>
    </Box>
  );
};

export default withStyles(styles)(ExampleComponent);
Run Code Online (Sandbox Code Playgroud)

应用程序.tsx

import * as React from "react";
import { ThemeProvider, createMuiTheme } from "@material-ui/core";
import ExampleComponent from "./ExampleComponent";

const theme = createMuiTheme();

function App() {
  return (
    <ThemeProvider theme={theme}>
      <ExampleComponent title="Root" />
      <ThemeProvider theme={theme}>
        <ExampleComponent title="Nested" />
      </ThemeProvider>
    </ThemeProvider>
  );
}

export default App;
Run Code Online (Sandbox Code Playgroud)

在 ExampleComponent 中,我 console.log 生成的类对象。

我想使用嵌套的 ThemeProvider 并覆盖组件内的类,而不管 ThemeProvider 是什么。我错过了什么或者这是不可能的吗?

Rya*_*ell 7

当您使用嵌套主题时,您无法可靠地使用 Material-UI 的全局类名(例如.MuiStepIcon-root.MuiStepIcon-active)。在嵌套主题中,“Mui...”类名称必须不同,以避免与顶级主题的 CSS 类发生冲突,因为嵌套主题会导致“Mui...”类的某些 CSS 发生冲突变得不同。

您可以使用以下语法来成功匹配嵌套主题中出现的 Mui 类名称的后缀版本:

const styles = createStyles({
  button: {
    '& [class*="MuiStepIcon-root"][class*="MuiStepIcon-active"]': {
      fill: "red"
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

使用嵌套主题编辑 withStyles

相关回答: