Material-ui-next中withStyles装饰器无法正常工作的问题求助
看起来你遇到了withStyles注入失败的问题,导致this.props.classes是undefined,进而读取root属性时报错。我帮你梳理几个最常见的排查方向和解决方案:
检查withStyles的导出包裹是否正确
这是最容易犯的错误:确保你的组件最终是被withStyles(styles)包裹后导出的,而不是直接导出组件本身。比如:// 错误写法:直接导出组件,没有用withStyles包裹 export default Respondent; // 正确写法:用withStyles(styles)装饰后再导出 export default withStyles(styles)(Respondent);验证styles对象的定义是否合法
确保你的styles是一个有效的样式对象(或返回样式对象的函数),并且确实包含root这个键。比如:// 正确的函数式样式(推荐,可获取theme) const styles = (theme: Theme) => ({ root: { padding: theme.spacing(2), backgroundColor: '#fff' } }); // 或者直接定义样式对象 const styles = { root: { padding: '16px', backgroundColor: '#fff' } };同时要确认styles变量没有被误写(比如写成
style而非styles),也没有被意外赋值为undefined。检查TypeScript的props类型定义
因为你用的是TypeScript,需要确保组件的props类型包含classes属性。可以用Material-UI提供的WithStyles类型来自动推断:import { withStyles, WithStyles } from '@material-ui/core/styles'; // 定义你的样式 const styles = { root: { /* ... */ } }; // 让Props继承WithStyles,自动包含classes类型 interface RespondentProps extends WithStyles<typeof styles> { // 其他自定义props } class Respondent extends React.Component<RespondentProps> { render() { // 现在this.props.classes会被正确推断,不会出现undefined return <div className={this.props.classes.root}>...</div>; } }如果没有正确定义类型,TypeScript可能会阻止props的传递,或者导致运行时的意外问题。
排查高阶组件的顺序问题
如果你的组件同时使用了多个高阶组件(比如Redux的connect),要确保withStyles是最靠近组件的那个。比如:// 正确顺序:先包裹withStyles,再包裹connect export default connect(mapStateToProps)(withStyles(styles)(Respondent)); // 错误顺序:connect在内层的话,withStyles的classes可能无法被传递到组件 // export default withStyles(styles)(connect(mapStateToProps)(Respondent));确认withStyles的导入路径正确
确保你是从@material-ui/core/styles导入withStyles,而不是旧版的material-ui/styles(因为你用的是material-ui-next,也就是v4版本,对应@material-ui/core):import { withStyles } from '@material-ui/core/styles';
内容的提问来源于stack exchange,提问作者Ivan Sukhetskyi

