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,请将ThemeProvider
、createTheme
和makeStyles
导入路径从:
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
/sx
API Asrecommended。
相关答案
- Difference between @mui/material/styles and @mui/styles?
- Cannot use palette colors from MUI theme
- MUI createTheme is not properly passing theme to MUI components
相关文章