我有一个使用 Create React App 创建的 React 应用程序,并使用 @material-ui/core npm 包进行主题化。
为了自定义组件,我使用 MaterialUI 提供的 withStyles 高阶组件。
根据文档它支持嵌套的 ThemeProvidershttps://material-ui.com/customization/theming/#nesting-the-theme https://material-ui.com/customization/theming/#nesting-the-theme.
但在子 ThemeProvider withStyles 内部不会应用类。
这是一个演示该问题的基本应用程序 ->https://codesandbox.io/s/vibrant-tree-eh83d 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);
App.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;
在 ExampleComponent 中,我 console.log 生成的类对象。
我想使用嵌套的 ThemeProvider 并覆盖组件内的类,而不管 ThemeProvider 是什么。
我错过了什么或者这是不可能的吗?