本文介绍了MUI-makeStyles-无法读取未定义的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习MUI,在课程中,讲师要求我只设计一个组件的样式,而不是整个主题的样式。

为此,它使用makeStyles函数并传播theme.mixins.toolbar。问题是,当我执行此操作时,出现以下错误:

TypeError: Cannot read properties of undefined (reading 'toolbar')

本课程显然是版本4,而我使用的是版本5。尽管如此,我的代码似乎遵循文档要求的更改。那么,导致此错误的原因可能是什么?

app.js

import "./App.css";
import Header from "./components/ui/Header";
import { ThemeProvider } from "@material-ui/core/styles";
import theme from "./components/ui/Theme";

function App() {
    return (
        <ThemeProvider theme={theme}>
            <Header />
        </ThemeProvider>
    );
}

export default App;

Theme.js

import { createTheme } from "@material-ui/core/styles";

const arcBlue = "#0B72B9";
const arcOrange = "#FFBA60";

export default createTheme({
    typography: {
        h3: {
            fontWeight: 100,
        },
    },
    palette: {
        common: {
            blue: `${arcBlue}`,
            orange: `${arcOrange}`,
        },
        primary: {
            main: `${arcBlue}`,
        },
        secondary: {
            main: `${arcOrange}`,
        },
    },
});

Header/index.jsx

import React from "react";
import AppBar from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import useScrollTrigger from "@mui/material/useScrollTrigger";
import Typography from "@mui/material/Typography";
import { makeStyles } from "@material-ui/styles";

function ElevationScroll(props) {
    const { children, window } = props;
    const trigger = useScrollTrigger({
        disableHysteresis: true,
        threshold: 0,
        target: window ? window() : undefined,
    });

    return React.cloneElement(children, {
        elevation: trigger ? 10 : 0,
    });
}

const useStyles = makeStyles((theme) => ({
    toolbarMargin: { ...theme.mixins.toolbar },
}));

function Header() {
    const classes = useStyles();
    return (
        <React.Fragment>
            <ElevationScroll>
                <AppBar color="primary">
                    <Toolbar>
                        <Typography variant="h3" component="h3">
                            Nome de teste
                        </Typography>
                    </Toolbar>
                </AppBar>
            </ElevationScroll>
            <div className={classes.toolBarMargin} />
        </React.Fragment>
    );
}

export default Header;

推荐答案

由于您使用的是v5,请将ThemeProvidercreateThememakeStyles导入路径从:

更改为
import { ThemeProvider, createTheme, makeStyles } from "@material-ui/core/styles";

收件人:

import { ThemeProvider, createTheme } from "@mui/material/styles";
import { makeStyles } from "@mui/styles";

@material-ui/core是v4包,@mui/material是v5等效包。两个版本的API不兼容。在v5中,makeStyles也被移到名为@mui/styles的遗留包中,如果您在新项目中使用MUI v5,则MUI团队应该完全切换到styled/sxAPI Asrecommended

相关答案

这篇关于MUI-makeStyles-无法读取未定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 09:42