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

React新手求助:为何出现classes未定义运行时错误

解决React中classes未定义的错误

问题原因

你定义了styles样式对象,但没通过Material-UI的withStyles高阶组件把样式注入到组件的props里,导致props.classes为undefined,访问classes.table自然报错。

解决步骤

  1. 导入withStyles:从Material-UI的样式包中导入withStyles工具
  2. 包裹组件:用withStyles(styles)包裹你的MyTable组件再导出
  3. 确保props接收:组件内正常解构classes即可

修改后的完整代码示例

import { withStyles } from '@material-ui/core/styles';
// 记得导入Box、TableContainer、Paper、Table等所需组件

const styles = (theme) => ({
    root: {
      width: "100%",
      marginTop: theme.spacing.unit * 3,
      overflowX: "auto"
    },
    table: {
      minWidth: 700
    },
    tableRow: {
      "&.Mui-selected, &.Mui-selected:hover": {
        backgroundColor: "purple",
        "& > .MuiTableCell-root": {
          color: "yellow"
        }
      }
    }
  });

function MyTable(props) {
    const { classes } = props;
    return (
        <div>
            <Box>
                <TableContainer component={Paper}>
                    <Table className={classes.table}>
                        {/* 补充你的表格内容 */}
                    </Table>
                </TableContainer>
            </Box>
        </div>
    );
}

export default withStyles(styles)(MyTable);

额外说明

如果使用的是Material-UI v5版本,官方更推荐使用styled组件或sx属性来处理样式,但如果要继续用withStyles,需要从@material-ui/styles包中导入,而非@material-ui/core/styles。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 16:52:20