【问题标题】:React Material UI : 'theme' is not defined no-undefReact Material UI:“主题”未定义 no-undef
【发布时间】:2020-07-05 19:24:35
【问题描述】:

我正在使用 material-ui 创建一个简单的反应应用程序。我正在使用 MuiThemeProvider 和 ThemeProvider 作为主题。

App.js

import React from 'react';
import { createMuiTheme,  MuiThemeProvider } from '@material-ui/core/styles';
import { ThemeProvider } from '@material-ui/styles';
import { CssBaseline } from '@material-ui/core';
import { Topic } from './dashboard/components/drawer/topic.js' 

const theme = createMuiTheme({
    palette : {
        type : 'dark',
        background : {
            default : "#000000"
        },
        secondary : {
            main : '#E19A4C'
        }
    }
})

function App() {
    return (
        < MuiThemeProvider theme={theme}>
            <ThemeProvider theme={theme}>
                <CssBaseline />
                <div className="App">
                    <Dashboard />
                    <Topic />
                </div>
            </ThemeProvider>
        </ MuiThemeProvider>
    );
}

export default App;

主题.js

import React, { Component } from 'react';
import { Typography, makeStyles, Box, Paper } from '@material-ui/core';

const style = makeStyles(theme => ({
    paper : {
        background : '#ff00ff'
    }
}))

export const Topic = (props) => {

    const classes = style()

    return (
        <div>
            <Paper className={classes.box}>
                <Typography variant="h6" component="h6" gutterBottom>
                    {props.data}
                </Typography>
            </Paper>
        </div>
    )
}

export default Topic

我收到错误Uncaught ReferenceError: theme is not defined

我在 makeStyles 中尝试过 { withTheme : true } 但它不起作用。

将主题作为道具发送有效,但不推荐。 有人可以帮忙吗?

【问题讨论】:

  • 如果您没有收到通知,我会用额外的信息更新我的答案。看看吧。

标签: javascript reactjs material-ui react-hooks


【解决方案1】:

在你的 Topic.js 文件中尝试像这样使用 useTheme 钩子:

import React, { Component } from 'react';
import { Typography, makeStyles, Box, Paper } from '@material-ui/core';
import { useTheme } from '@material-ui/core/styles';

const style = makeStyles(theme => ({
    paper : {
        background : '#ff00ff'
    }
}))

export const Topic = (props) => {

    const classes = style()
    const theme = useTheme();

    return (
        <div>
            <Paper className={classes.box}>
                <Typography variant="h6" component="h6" gutterBottom>
                    {props.data}
                </Typography>
            </Paper>
        </div>
    )
}

export default Topic

现在您可以从主题变量访问您在 App.js 中创建的主题(例如 const 主题

【讨论】:

  • 我应该把它作为道具发送给makeStyles吗?因为简单地添加这个功能组件是行不通的。
  • 无需将主题作为道具传递。 ThemeProvider 使用 React 上下文将主题传递给孩子。通过使用 useTheme 挂钩,您可以在子组件中使用上下文值(主题)。我用额外的信息更新了我的答案,看看。
猜你喜欢
  • 2020-12-21
  • 2019-11-10
  • 2019-10-05
  • 2018-03-18
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
相关资源
最近更新 更多