【问题标题】:How can I use 'theme' made with 'createMuiTheme()' inside 'makeStyles()'?如何在“makeStyles()”中使用“createMuiTheme()”制作的“主题”?
【发布时间】:2021-08-19 13:08:46
【问题描述】:

我使用createMuiTheme() 制作了customTheme,并在<ThemeProvider> 中使用了它。 现在,我想在makeStyles() 函数中使用customTheme 制作一些自定义样式。但是makeStyles() 没有得到我的customTheme。它获取默认主题。

代码:

import React from 'react';

import { createMuiTheme, makeStyles, ThemeProvider } from '@material-ui/core';

const customTheme = createMuiTheme({
  palette: {
    primary: {
      main: '#f0f'
    },
  }
});

const useStyles = makeStyles((theme) => ({
  box: {
    height: '100px',
    width: '100px',
    backgroundColor: theme.palette.primary.main
  }
}));

export default function App() {

  const classes = useStyles();

  return (
    <ThemeProvider theme={customTheme}>

      <div className={classes.box}>
        makeStyles
      </div>

      <div style={{
        height: '100px',
        width: '100px',
        backgroundColor: customTheme.palette.primary.main
      }}>
        inline style
      </div>

    </ThemeProvider>
  );
}

截图: Screenshot Image

如屏幕截图所示,第一个 &lt;div&gt; 具有使用 makeStyles 的 Material-UI 的默认深蓝色。

第二个&lt;div&gt;有自定义颜色,即使用内联样式。

那么,如何在makeStyles() 中使用customTheme

【问题讨论】:

    标签: material-ui makestyles


    【解决方案1】:

    尝试 ThemeProvider 包裹 App 组件,根据我的理解,提供的主题将应用于包裹在其下的反应组件。因为“makeStyles div”只是一个元素样式并没有应用到它。

    代码沙盒链接 - https://codesandbox.io/s/mui-custom-theme-f354x

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 2021-05-06
      • 2023-03-15
      • 2019-06-20
      • 2021-08-19
      • 2020-01-13
      相关资源
      最近更新 更多