【发布时间】:2017-05-13 04:14:03
【问题描述】:
我有一个从父级一直到组件层次结构中子级的函数。通常这不会有太大问题,但我需要从孩子那里接收一个参数。 我目前收到此错误消息:
Uncaught (in promise) TypeError: this.props.myFunction is not a function.
这是我正在做的示例代码:
class SomeComponent extends Component{
constructor(props){
super(props);
//does whatever stuff
this.myFunction = this.myFunction.bind(this);
}
//(only applicable to raw and normal forms)
myFunction(param){
console.log('do something: ', param);
}
render(){
return (<div><ChildComponent1 myFunction={()=>this.myFunction()}/></div>)
}
}
class ChildComponent1{
render(){
return (<div><ChildComponent2 myFunction={()=>this.props.myFunction()}/></div>)
}
}
class ChildComponent2{
render(){
return (<Button onClick={()=>this.props.myFunction(param)}>SomeButton</Button>)
}
}
总结一下:我将 myFunction 作为 prop 从 SomeComponent 一直传递到 ChildComponent2,我希望在单击按钮时调用它并从 ChildComponent2 传递参数.
谢谢!
【问题讨论】:
-
实际的问题可能是您的 childComponent1 并没有真正转发任何可能被调用的参数,也许您应该重构它,使您转发的函数是'最终不是箭头函数
标签: javascript reactjs