材质UI:在Reaction类组件中使用主题 [英] Material UI: Use theme in React Class Component
本文介绍了材质UI:在Reaction类组件中使用主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找类似ThemeConsumer的东西(可能不存在)。我已经使用了Reaction组件,并且正在使用withStyles()
高阶组件注入自定义样式。documentation中对此进行了很好的描述,但是我没有找到任何使用主题的示例。
我有一些包含ThemeProvider的基本组件。这表示任何MUI组件都受其影响。
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const theme = getTheme(prefersDarkMode);
return (
<ThemeProvider theme={theme}>
...
</ThemeProvider>
)
我还在makeStyles()
中使用了一些功能组件来创建带有所提供主题的样式。
const useStyles = makeStyles(theme => ({
// here I can use theme provided by ThemeProvider
});
但它不能用于类组件。所以我使用withStyles()
hoc。
const styles = {
// I would like to use here provided theme too
}
export default withStyles(styles)(SomeComponent);
我的问题摘要:
如何在类组件中使用提供的主题?
推荐答案
withStyles
支持与makeStyles
相似的语法:
const styles = theme => ({
// here I can use theme provided by ThemeProvider
});
export default withStyles(styles)(SomeComponent);
这里有一个简单的工作示例:
import React from "react";
import { withStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
const StyledPaper = withStyles(theme => ({
root: {
backgroundColor: theme.palette.secondary.main
}
}))(Paper);
export default function App() {
return (
<StyledPaper className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</StyledPaper>
);
}
这篇关于材质UI:在Reaction类组件中使用主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文