MUI下拉框样式报错:Object(...) is not a function求助
解决MUI下拉框自定义样式时「Object(...) is not a function」错误
这个错误几乎都是MUI版本与makeStyles导入方式不匹配导致的,以下分两种场景给出解决方案:
场景1:使用MUI v4(依赖包为@material-ui/core)
- 确认依赖安装正确,无版本冲突:
检查package.json中@material-ui/core版本为4.x.x,同时确保react版本≥16.8.0 - 确保在组件内正确调用样式钩子:
你的样式文件导出的是makeStyles创建的钩子,必须在函数组件内部调用它:import dropDownStyle from './dropDownStyle'; function MyDropdown() { const classes = dropDownStyle(); // 必须在组件内部调用 return ( <FormControl className={classes.formControl}> {/* 下拉框组件内容 */} </FormControl> ); } - 确保组件被
ThemeProvider包裹:
从@material-ui/core/styles导入ThemeProvider和createTheme,在根组件包裹:import { ThemeProvider, createTheme } from '@material-ui/core/styles'; const theme = createTheme(); function App() { return ( <ThemeProvider theme={theme}> <MyDropdown /> </ThemeProvider> ); }
场景2:使用MUI v5(依赖包为@mui/material)
MUI v5默认移除了@mui/material/styles中的makeStyles,需要单独安装配套包:
- 安装
@mui/styles:npm install @mui/styles # 或 yarn add @mui/styles - 修改样式文件的导入路径:
// 替换原来的导入 import { makeStyles } from "@mui/styles"; - 同样需要在
ThemeProvider(v5版本)下使用:import { ThemeProvider, createTheme } from '@mui/material/styles'; const theme = createTheme(); function App() { return ( <ThemeProvider theme={theme}> <MyDropdown /> </ThemeProvider> ); }
额外检查点
- 不要同时安装
@material-ui/core和@mui/material,避免版本冲突 - 确认
react和react-dom版本符合MUI要求:v5要求≥16.8.0,v4要求≥16.8.0
内容的提问来源于stack exchange,提问作者Nui
相关产品推荐
相关产品推荐

