React Material-UI断点运行时报错:Cannot read properties of undefined (reading 'down')
问题排查与解决
你的代码与错误信息
组件代码
const RightComponent=styled(Box)(({theme})=>{ width:'17%', background:'#ffffff', padding:5, marginTop:10, marginLeft:10, textAlign:'center', [theme.breakpoints.down('md')]:{ display:'none' } });
错误信息
TypeError: Cannot read properties of undefined (reading 'down')
问题原因
- 组件未被MUI
ThemeProvider包裹,导致theme参数未正确注入,theme.breakpoints为undefined。 - 自定义MUI主题时遗漏了
breakpoints配置,或配置错误。
解决步骤
1. 用ThemeProvider包裹组件
确保你的RightComponent被ThemeProvider包裹,根组件示例:
import { ThemeProvider, createTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import styled from '@emotion/styled'; // 创建默认主题(可自定义) const theme = createTheme(); function App() { return ( <ThemeProvider theme={theme}> <RightComponent /> </ThemeProvider> ); } export default App;
2. 检查自定义主题配置
如果使用自定义主题,确保breakpoints配置正确,可继承默认值:
const customTheme = createTheme({ breakpoints: { values: { xs: 0, sm: 600, md: 900, lg: 1200, xl: 1536, }, }, // 其他自定义配置... });
3. 验证依赖完整性
确认已安装必要依赖:
npm install @mui/material @emotion/react @emotion/styled # 或 yarn yarn add @mui/material @emotion/react @emotion/styled
内容的提问来源于stack exchange,提问作者Ganesh Turate
相关产品推荐
相关产品推荐

