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

React子组件props在state中可正常读取,按钮触发函数中为undefined

问题原因

这是React Class组件常见的this指向丢失问题:

  • 你定义的message、updateInputValue都是类的普通方法,直接将this.message作为onClick事件回调传递时,方法的执行上下文会脱离组件实例,导致内部的this指向undefined,自然读不到this.props。
  • 类属性初始化state时是在组件实例化阶段执行,此时this天然指向当前组件实例,所以可以正常读取this.props。

解决方案

以下3种常用修复方式任选其一即可:

方案1:事件绑定时用箭头函数包裹

在onClick绑定位置用箭头函数包裹方法调用,箭头函数会继承外层render方法的this指向:

<button id="add" onClick={() => this.message()} className="form-control btn btn-success" >➕</button>

方案2:构造函数内提前绑定this

在组件构造函数中给方法绑定当前实例的this:

class Search extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      inputValue : this.props.inputValue
    };
    // 绑定实例this
    this.message = this.message.bind(this);
    this.updateInputValue = this.updateInputValue.bind(this);
  }

  // 后续方法逻辑保持不变
  message(){
    console.log(this.props)
  }
  // ...其余代码
}

方案3:将方法定义为箭头函数类属性

直接把普通方法改成箭头函数写法,箭头函数的this会自动绑定到当前类实例,无需额外绑定操作,是目前开发中最常用的方案:

// 改为箭头函数写法
message = () => {
  console.log(this.props)
  // this.props.sendMessage("HI")
}

updateInputValue = (event) => {
  this.setState({
    inputValue : event.target.value
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:54:04