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

ReactJS Material UI TypeScript withStyles警告:classes属性类型不符

解决Material UI withStyles的classes prop类型警告

嘿,这个警告的原因一眼就能看出来——你给classes设置的默认值和withStyles高阶组件的预期类型冲突了!

问题根源

withStyles(styles)的核心作用就是把你写的styles函数处理成对象形式的样式类集合,然后自动注入到组件的props里。但你在static defaultProps里把styles这个函数本身赋值给了classes,这就导致传入的classes是function类型,而WithStyles期望的是object类型,TypeScript自然就抛出了这个类型不匹配的警告。

具体修改步骤

  1. 删除错误的默认值
    直接删掉这行画蛇添足的代码:

    static defaultProps = {
      classes: styles
    };
    

    withStyles已经会自动处理并注入正确的classes对象,完全不需要手动指定默认值。

  2. 简化Props接口
    AppProps继承的WithStyles<typeof styles>已经包含了类型正确的classes属性,所以你不需要再单独声明classes: any;,把这行从接口里删掉就行,避免类型重复和混淆。

修改后的完整代码

import React from "react";
import { CssBaseline, Theme, createStyles, Paper, Typography, withStyles, WithStyles, withTheme } from "@material-ui/core";

const styles = (theme: Theme) => createStyles({
  layout: {
    width: "800",
    marginLeft: theme.spacing(2),
    marginRight: theme.spacing(2),
    [theme.breakpoints.up(800 + theme.spacing(2) * 2)]: {
      width: 800,
      marginLeft: "auto",
      marginRight: "auto"
    }
  },
  paper: {
    marginTop: theme.spacing(3),
    marginBottom: theme.spacing(3),
    padding: theme.spacing(2),
    [theme.breakpoints.up(800 + theme.spacing(3) * 2)]: {
      marginTop: theme.spacing(6),
      marginBottom: theme.spacing(6),
      padding: theme.spacing(3)
    }
  }
});

// 简化接口,WithStyles已经包含正确的classes类型
interface AppProps extends WithStyles<typeof styles> {}

class App extends React.Component<AppProps> {
  constructor(props: AppProps) {
    super(props);
  }

  render() {
    return (
      <React.Fragment>
        <CssBaseline />
        <main className={this.props.classes.layout}>
          <Paper className={this.props.classes.paper}>
            <Typography component="h1" variant="h4" align="center">
              Sub Head
            </Typography>
            Hello World
          </Paper>
        </main>
      </React.Fragment>
    );
  }
}

export default withTheme(withStyles(styles)(App));

这样修改后,withStyles会正常把编译好的样式类对象注入到组件props中,既符合TypeScript的类型要求,也能彻底消除那个警告,你的样式依然会正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 21:49:05