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

React类组件未在构造器传props,为何render()中this.props未定义?

React类组件中this.props为undefined的原因分析

你的代码里this.props变成undefined,核心原因是构造函数没有将props传递给super()。

React的Component基类构造函数需要接收props参数,才能完成实例上this.props的初始化绑定。如果你的自定义构造函数调用super()时不传props,基类构造函数就无法把外部传入的props挂载到当前组件实例上,后续在render等方法里访问this.props自然就是undefined。

看你的代码示例:

class App extends React.Component {
  constructor(){
    super() // 未传递props给父类构造函数
  }
  render (){
    console.log(this.props) // 结果为undefined
  }
}
<App name="ashwin"/>

解决方法

有两种简单的修复方式:

  • 在构造函数中把props传给super():
constructor(props){
  super(props)
}
  • 直接删除自定义的构造函数——如果你的组件不需要在构造函数里做初始化状态、绑定事件等操作,React会使用默认构造函数,它会自动把props传递给基类,确保this.props能正常访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:50:34