gpt4 book ai didi

reactjs - Material UI 嵌套主题提供者与 Styles HOC 决裂

转载 作者:行者123 更新时间:2023-12-05 01:37:13 24 4
gpt4 key购买 nike

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

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

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

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

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

ExampleComponent.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 中,我控制台记录生成的类对象。

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

最佳答案

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

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

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

Edit withStyles with nested themes

相关回答:

关于reactjs - Material UI 嵌套主题提供者与 Styles HOC 决裂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61193095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com