Material-UI | 在 makeStyles 中使用`theme`

Gal*_*eld 6 javascript css reactjs material-ui

我正在尝试获取一个muiTheme,通过它传递给一个组件ThemeProvider 并传递给它的子组件,然后在它们创建的类对象中使用主题的属性makeStyles。

具体来说,这些是我拥有的组件/文件:

  • 组件LeftSection| 渲染Subsection(如下所述)
  • muiTheme LefSectionTheme| 在类对象中使用LeftSection

  • 组件RightSection| 渲染Subsection

  • 多主题 RightSectionTheme

  • 成分 Subsection

我想要做的是makeStyles()在每个组件中添加一个创建的类对象,并且每个组件都使用主题的属性。我没有在这里发布代码,因为我尝试了很多函数的组合,而且我想我对其中一些函数的工作方式的理解有一个漏洞。

所以这是一个没有任何类的再现:LeftSection 和 RightSection 渲染带有它们的主题的 Subsection - 为此我想添加类。

这是Subsection我要使用类的组件的代码:

import React from "react";
import { useTheme } from "@material-ui/styles";

function Subsection(props) {
  const theme = useTheme();
  return (
    <p
      style={{
        color: theme.palette.primary.main
      }}
    >
      test
    </p>
  );
}

export default Subsection;
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Rya*_*ell 11

以下是使用将主题用于此样式的类的语法:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles(theme => ({
  paragraph: {
    color: theme.palette.primary.main
  }
}));
function Subsection(props) {
  const classes = useStyles();
  return <p className={classes.paragraph}>test</p>;
}

export default Subsection;
Run Code Online (Sandbox Code Playgroud)

编辑 serene-pond-t07i1

如果没有看到您之前尝试过的代码,我很难知道您的理解中可能存在哪些具体漏洞,因此如果您对此有具体问题,我可以添加更多解释/参考。

  • 谢谢,它有效。:) 我会尝试在我的代码库中实现它。 (2认同)