【问题标题】:Material-UI | Using `theme` in makeStyles材质-UI |在 makeStyles 中使用“主题”
【发布时间】:2019-12-09 14:12:35
【问题描述】:

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

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

  • 组件LeftSection |呈现Subsection(如下所述)
  • muiTheme LefSectionTheme |用于LeftSection中的类对象

  • 组件RightSection |渲染Subsection

  • muiTheme RightSectionTheme

  • 组件Subsection

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

所以这是一个没有任何类的复制品:LeftSection and RightSection rendering Subsection with their themes - 我想为此添加类。

这是我要使用类的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;

我该怎么做?

【问题讨论】:

    标签: javascript css reactjs material-ui


    【解决方案1】:

    以下是使用主题的类的语法:

    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;
    

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

    【讨论】:

    • 谢谢,它有效。 :) 我会尝试在我的代码库中实现它。
    猜你喜欢
    • 2020-08-19
    • 2021-03-23
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2021-09-02
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多