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
相关产品推荐
相关产品推荐

