如何从组件中访问主题面板?

Fab*_*ian 5 material-ui

我正在尝试构建一个呈现div显示错误的组件。

function ErrorDiv(props) {
  return (
    <Card>
      <Typography>{props.message}</Typography>
    </Card>
  );
}
Run Code Online (Sandbox Code Playgroud)

我想设置<Card>背景颜色为palette.error.main<Typography>字体颜色为白色的样式。

但是,我不确定如何访问主题颜色。是否有palette暴露的变量?或者我应该在我的主题创建模块中将单个颜色导出为字符串,然后导入颜色以供此处使用?

Luk*_*vey 7

这是有关此文档的链接

下面是一个使用 withStyles 的例子:

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

const styles = theme => ({
  card: {
    background: theme.palette.error.main,
    color: '#fff'
  }
})

function ErrorCard({ classes }) {
  return (
    <div>
      <Card className={classes.card}>
        <Typography variant="title" color="inherit">
          Something went wrong!!
        </Typography>
      </Card>
    </div>
  )
}
export default withStyles(styles)(ErrorCard)
Run Code Online (Sandbox Code Playgroud)

代码沙盒上的实时示例


小智 5

形成文档:使用主题钩子

import { useTheme } from '@material-ui/styles';

function DeepChild() {
  const theme = useTheme();
  return <span>{`spacing ${theme.spacing}`}</span>;
}
Run Code Online (Sandbox Code Playgroud)

不是您的典型用例,但有必要访问主题中的颜色数组,例如