Material UI v5使用makeStyles时报错Cannot read 'breakpoints' of undefined
错误原因
你遇到的报错是MUI v5版本架构调整导致的,核心有两点:
@mui/styles是MUI v5的遗留兼容方案,默认不会自动注入主题对象,你拿到的theme自然是undefined- 即使你用了
ThemeProvider,大概率要么是没有将根组件完整包裹,要么是导入的ThemeProvider来源错误、没有传入正确的theme属性
解决方案
方案1(推荐,无需使用makeStyles)
直接用MUI v5原生支持的sx属性实现样式,自带主题访问能力,不需要额外引入hook,写法更简洁:
import "./welcome.css"; import * as React from "react"; import { Typography, Grid } from "@mui/material"; const Welcome = () => { const PF = process.env.REACT_APP_PUBLIC_FOLDER; return ( <div style={{ backgroundImage: `URL(${PF + "back.jpg"})`, backgroundRepeat: "no-repeat", backgroundPosition: "center", backgroundSize: "cover", height: "calc(100vh)", }} > <Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}> <Grid item xs={12} md={6}> <div className="gridLeft"> <Typography>Side One </Typography> </div> </Grid> <Grid item xs={12} md={6}> <div sx={{ height: "350px", backgroundColor: "black", opacity: 0.3, borderRadius: 20, padding: 10, color: "white", // 断点直接配置,和原逻辑完全一致:md及以上宽度50%,小于md宽度100% width: { md: "50%", xs: "100%" } }} > <Typography>Side Two </Typography> </div> </Grid> </Grid> </div> ); }; export default Welcome;
方案2(坚持使用makeStyles)
在你的项目入口文件(一般是index.js/App.js)中,用正确的ThemeProvider包裹整个应用:
// 注意ThemeProvider和createTheme要从@mui/material/styles导入,不要用@mui/styles下的 import { ThemeProvider, createTheme } from '@mui/material/styles'; import CssBaseline from '@mui/material/CssBaseline'; import Welcome from './Welcome'; // 创建主题对象,可自定义配置 const theme = createTheme(); function RootApp() { return ( <ThemeProvider theme={theme}> <CssBaseline /> <Welcome /> </ThemeProvider> ); } export default RootApp;
同时确保你已经安装了@mui/styles依赖,未安装的话执行npm install @mui/styles即可。
内容的提问来源于stack exchange,提问作者Hemmyhtec Creatives
相关产品推荐
相关产品推荐

