React Material UI:“主题”未定义 no-undef

add*_*ddy 4 javascript reactjs material-ui react-hooks

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

应用程序.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;
Run Code Online (Sandbox Code Playgroud)

主题.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
Run Code Online (Sandbox Code Playgroud)

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

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

将主题作为道具发送是可行的,但不建议这样做。有人可以帮忙吗?

IVI*_*osi 6

在您的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
Run Code Online (Sandbox Code Playgroud)

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