Javascript 无法读取属性';道具';null-Reactjs的定义
基本上,我想从子组件中的父组件调用函数。该函数将更改父组件的状态 我在父组件中创建了一个处理程序,并将其作为prop传递给子组件。 现在我想在子组件中调用它 家长:Javascript 无法读取属性';道具';null-Reactjs的定义,javascript,reactjs,Javascript,Reactjs,基本上,我想从子组件中的父组件调用函数。该函数将更改父组件的状态 我在父组件中创建了一个处理程序,并将其作为prop传递给子组件。 现在我想在子组件中调用它 家长: state = { formstep: '1'} constructor(props) { super(props) this.handler = this.handler.bind(this) } handler(e) { e.preventDefault() this.setState
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} />
)
}
state={formstep:'1'}
建造师(道具){
超级(道具)
this.handler=this.handler.bind(this)
}
处理程序(e){
e、 预防默认值()
这是我的国家({
formstep:'2'
})
}
渲染(){
返回(
)
}
在child中,当我试图调用handler函数时,它说
无法读取null的属性“props”
儿童:
handleClick() {
//Saving Some data from form
//and calling parent function
this.props.handler;
}
render () {
return (
<button onClick={this.handleClick}>Continue</button>
)
}
handleClick(){
//从表单中保存一些数据
//并调用父函数
this.props.handler;
}
渲染(){
返回(
继续
)
}
在子组件中,您需要正确绑定上下文:
<button onClick={this.handleClick.bind(this)}>Continue</button>
绑定问题在child onClick函数中,在google上搜索将导致此问题的大量重复
this.handleClick()}>继续this with()
工作非常出色。谢谢:)
this.handleClick = this.handleClick.bind(this)
// => <button onClick={this.handleClick}>Continue</button>
<button onClick={() => this.handleClick()}>Continue</button>
handleClick() {
this.props.handler();
// note ------^
}