通过reactjs上的props传递带参数的函数 [英] Passing a function with parameters through props on reactjs
问题描述
我有一个函数,它从父级一直到组件层次结构中子级的子级。通常这不会是一个太大的问题,但我需要从孩子那里收到一个参数。
我目前收到此错误消息:Uncaught(在promise中)TypeError:this.props.myFunction不是函数。
I have a function that comes from a parent all the way down to a the child of a child in a component hierarchy. Normally this wouldn't be too much of a problem, but I need to receive a parameter from the child. I am currently getting this error message: Uncaught (in promise) TypeError: this.props.myFunction is not a function.
这是一个示例代码我在做什么:
Here is an example code to what I a doing:
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传递参数。
So just to some it up: I am passing myFunction as a prop from SomeComponent all the way down to ChildComponent2, in which I want it called whenever a button is clicked and to pass a parameters from ChildComponent2.
谢谢!
推荐答案
我不明白为什么你会得到那个错误,但你应该做 myFunction = {this.myFunction}
和 myFunction的= {this.props.myFunction}
:
I don't see why you would get that error, but you should be doing myFunction={this.myFunction}
and 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).
这篇关于通过reactjs上的props传递带参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!