You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Material UI:类组件中使用useStyles报错无法读取root属性如何解决

报错原因
  • useStyles是Material UI封装的React Hook,Hook仅支持在函数组件、自定义Hook中调用,类组件无法直接使用
  • 你编写的代码没有将样式生成的classes对象注入到类组件的props中,this.props.classes为undefined,调用classes.root自然触发空指针报错
解决方案

方案1:使用Material UI专门为类组件提供的withStyles高阶组件(推荐)

直接替换原有makeStyles写法,用withStyles包裹类组件导出,样式会自动注入到组件props的classes字段中:

import { withStyles } from '@material-ui/core/styles';
// MUI v5 版本改为 import { withStyles } from '@mui/styles';

// 原样式逻辑直接抽离为独立的styles对象
const styles = (theme) => ({
  root: {
    flexGrow: 1,
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },
  title: {
    flexGrow: 1,
  },
});

class Navbar extends React.Component {
  render() {
    const { classes } = this.props;
    return(
      <div className={classes.root}>
        <AppBar position="static">
          <Toolbar>
            <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
              <MenuIcon />
            </IconButton>
            <Typography variant="h6" className={classes.title}>
              News
            </Typography>
            <Button color="inherit">Login</Button>
          </Toolbar>
        </AppBar>
      </div>
    )
  }
}

// 用withStyles包裹组件后导出
export default withStyles(styles)(Navbar);

方案2:外层包裹函数组件调用useStyles

如果不想修改原有makeStyles的写法,可以加一层函数组件作为中间层,在函数组件内调用useStyles后将classes作为props传入类组件:

import { makeStyles } from '@material-ui/core/styles';
// MUI v5 版本改为 import { makeStyles } from '@mui/styles';

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },
  title: {
    flexGrow: 1,
  },
}));

class Navbar extends React.Component {
  render() {
    const { classes } = this.props;
    return(
      <div className={classes.root}>
        <AppBar position="static">
          <Toolbar>
            <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
              <MenuIcon />
            </IconButton>
            <Typography variant="h6" className={classes.title}>
              News
            </Typography>
            <Button color="inherit">Login</Button>
          </Toolbar>
        </AppBar>
      </div>
    )
  }
}

// 外层加函数组件调用Hook传参
export default function NavbarWrapper() {
  const classes = useStyles();
  return <Navbar classes={classes} />
}
注意事项

MUI v5版本已将makeStyles、withStyles移到独立的@mui/styles包,使用前需要单独安装。长期来看建议将类组件重构为函数组件,更适配MUI后续的API迭代。

内容的提问来源于stack exchange,提问作者Farah10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:06:02