基本上我想在子组件中调用父组件的函数。该函数将更改父组件的状态。
我在父组件中创建了一个处理程序并将其作为道具传递给子组件。
现在我想在子组件中调用它。
Parent:
state = { formstep: '1'}
constructor(props) {
super(props)
this.handler = this.handler.bind(this)
}
handler(e) {
e.preventDefault()
this.setState({
formstep: '2'
})
}
render () {
return (
<Form1 handler = {this.handler} />
)
}
在孩子中,当我尝试调用处理函数时,它说
无法读取 null 的属性“props”
Child:
handleClick() {
//Saving Some data from form
//and calling parent function
this.props.handler;
}
render () {
return (
<button onClick={this.handleClick}>Continue</button>
)
}
在子组件中,您需要正确绑定上下文:
<button onClick={this.handleClick.bind(this)}>Continue</button>
或者更好地绑定在构造函数中:
this.handleClick = this.handleClick.bind(this)
// => <button onClick={this.handleClick}>Continue</button>
或将其作为方法调用:
<button onClick={() => this.handleClick()}>Continue</button>
最后,您需要实际调用回调:
handleClick() {
this.props.handler();
// note ------^
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)