材料UI。在React类组件中使用主题

问题描述 投票:2回答:2

我正在寻找像ThemeConsumer这样的东西(可能不存在)。我有一个React组件,我使用的是 withStyles() 高阶组件来注入自定义样式。这在 文件 但我没有找到任何使用主题的例子。


我有一些基础组件,其中包含 主题供应商. 这意味着任何一个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);

我的问题的总结。 我如何使用 题材 类组件中?

reactjs material-ui
2个回答
2
投票

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>
  );
}

Edit withStyles using theme


0
投票

一个装饰有 withStyles(styles) 受宠若惊 classes 注入的道具,可用于您的自定义样式。例如:如果你通过

import { Box } from "@material-ui/core"
import { withStyles } from "@material-ui/core/styles"

const styles = theme => ({
  myCustomClass: {
    color: theme.palette.tertiary.dark
  }
})

class myComponent extends Component {
  render() {
    const { classes, theme } = this.props
    // In last line, you see we have passed `{ withTheme: true }` option
    // to have access to the theme variable inside the class body. See it
    // in action in next line.

    return <Box className={classes.myCustomClass} padding={theme.spacing(4)} />
  }
}

export default withStyles(styles, { withTheme: true })(myComponent)

如果你通过 { withTheme: true } 选择 withStyles HOC,你会得到主题变量也被注入为一个道具。

如果你有其他的HOC(例如Redux的connect、Router等)应用到你的组件上,你可以这样使用。

export default withStyles(styles, { withTheme: true })(
   withRouter(connect(mapStateToProps)(myComponent))
)

关于这个话题更全面的解释可以在这篇文章中找到。在React函数和类组件中使用Material UI主题变量。.

© www.soinside.com 2019 - 2024. All rights reserved.