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

React类组件中如何正确使用connect()与withStyles()?

在React类组件中正确使用connect()和withStyles()的方法

嘿,我发现你代码里有个关键问题——你把用于函数组件的makeStyles Hook用到类组件里了,这肯定会报错的!makeStyles是React Hook,只能在函数组件或自定义Hook的顶层调用,类组件根本没法用它。咱们一步步来修正,给你正确的用法:

第一步:纠正样式定义方式(类组件要用withStyles)

类组件要搭配Material UI的withStyles高阶组件来使用样式,而不是makeStyles。你可以用createStyles辅助函数(能获得更好的类型提示,JS环境也可以直接写样式对象)来定义样式:

import React from 'react';
import { connect } from 'react-redux';
// MUI v4:从@material-ui/core/styles导入;MUI v5:从@mui/styles导入,需单独安装该包
import { withStyles, createStyles } from '@material-ui/core/styles';

// 定义样式(用createStyles包裹是为了TypeScript类型支持,JS环境可省略直接写对象)
const styles = createStyles((theme) => ({
  container: {
    padding: theme.spacing(3),
    color: theme.palette.text.primary,
    backgroundColor: theme.palette.background.paper,
  },
}));

第二步:编写类组件并接收样式props

withStyles会把生成的样式类名作为classes属性传给你的类组件,所以你需要从this.props里取出classes来使用:

class MyComponent extends React.Component {
  render() {
    // 从props中解构出withStyles传递的classes
    const { classes } = this.props;

    return (
      <div className={classes.container}>
        Stackoverflow
      </div>
    );
  }
}

第三步:正确组合connect和withStyles高阶组件

高阶组件的包裹顺序其实不影响功能,但通常把样式相关的HOC放在更靠近组件的位置(逻辑上先给组件加样式,再连接Redux)。两种写法都可以:

写法一:先withStyles,再connect(推荐)

const mapStateToProps = (state) => ({
  // 这里定义你需要从Redux state中映射的属性,比如:
  // userInfo: state.user.info
});

// 先给组件添加样式,再连接Redux
export default connect(mapStateToProps, null)(withStyles(styles)(MyComponent));

写法二:先connect,再withStyles

// 先连接Redux,再添加样式
export default withStyles(styles)(connect(mapStateToProps, null)(MyComponent));

关键注意事项

  • MUI版本差异:如果用的是Material UI v5,withStyles不在核心包了,需要单独安装@mui/styles包,用法和v4一致,但v5更推荐用Styled Components/Emotion方案,不过类组件依然可以用withStyles兼容。
  • 不要混用Hook和类组件:makeStyles、useTheme这些Hook只能在函数组件里用,类组件必须用对应的高阶组件方案(withStyles、withTheme)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:28:29