Material-ui报错:Module 'material-ui/styles'无导出成员withStyles求助
解决Material-UI中withStyles导入错误的问题
嘿,作为经常和Material-UI打交道的开发者,我太懂这种版本路径踩坑的滋味了!你遇到的Module 'material-ui/styles' has no exported members 'withStyles'错误,本质是包版本和导入路径不匹配导致的,咱们一步步来解决:
第一步:替换过时的依赖包
你提到的material-ui-next是Material-UI早期v1版本的测试包,现在早已被正式的@material-ui/core包取代,旧包不仅停止维护,路径规则也和正式包不一致。先把旧包卸载,安装正确的核心包:
# 卸载旧的测试包 npm uninstall material-ui material-ui-next # 安装正式的Material-UI核心包(兼容你熟悉的withStyles) npm install @material-ui/core
第二步:修正导入路径
原来的import { withStyles } from 'material-ui/styles';路径是错误的,正式包中withStyles的正确路径是@material-ui/core/styles,同时其他组件的导入也要同步修改,比如AppBar:
import React from 'react'; import PropTypes from 'prop-types'; // 修正withStyles的导入路径 import { withStyles } from '@material-ui/core/styles'; // 修正组件的导入路径 import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography';
第三步:可运行的示例代码
给你一个完整的可用示例,确保你能顺利跑通:
const styles = { root: { flexGrow: 1, margin: '20px' }, appBar: { backgroundColor: '#2196f3' }, title: { padding: '8px' } }; function CustomAppBar(props) { const { classes } = props; return ( <div className={classes.root}> <AppBar className={classes.appBar} position="static"> <Toolbar> <Typography variant="h5" className={classes.title}> 我的Material-UI页面 </Typography> </Toolbar> </AppBar> </div> ); } CustomAppBar.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(CustomAppBar);
额外建议:试试最新版MUI(v5)
如果你刚接触Material-UI,更推荐直接用最新的MUI v5,它把包名改成了@mui/material,官方已经不推荐用withStyles,转而推荐更灵活的styled组件或sx prop。如果非要在v5里用withStyles,需要额外安装依赖:
npm install @mui/material @mui/styles @emotion/react @emotion/styled
导入路径改成:
import { withStyles } from '@mui/styles';
不过用sx prop的代码会更简洁,比如上面的示例可以改成:
import React from 'react'; import AppBar from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import Typography from '@mui/material/Typography'; function CustomAppBar() { return ( <div sx={{ flexGrow: 1, margin: '20px' }}> <AppBar sx={{ backgroundColor: '#2196f3' }} position="static"> <Toolbar> <Typography variant="h5" sx={{ padding: '8px' }}> 我的MUI页面 </Typography> </Toolbar> </AppBar> </div> ); } export default CustomAppBar;
内容的提问来源于stack exchange,提问作者aromanarguello
相关产品推荐
相关产品推荐

