我有一个功能,它从父级一直到组件层次结构中子级的子级。通常,这不会有太大的问题,但是我需要从孩子那里接收一个参数。我目前收到此错误消息:
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作为道具传递SomeComponent给ChildComponent2,每次单击按钮并从中传递参数时,我都希望将其调用ChildComponent2。
SomeComponent
ChildComponent2
谢谢!
我不明白你为什么会得到这个错误,但你应该做的myFunction={this.myFunction}和myFunction={this.props.myFunction}:
myFunction={this.myFunction}
myFunction={this.props.myFunction}
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>) } }
Wrapping the function call inside another (arrow) function is just unnecessary and won’t forward the parameter properly (since all your intermediate arrow functions do not accept a parameter).