コンポーネント階層で、親から子の子に至るまでの関数があります。通常、これはそれほど問題にはなりませんが、子からパラメータを受け取る必要があります。私は現在このエラーメッセージを受け取っています:
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
。
ありがとう!
あなたがそのエラーになるだろう、なぜ私は見ませんが、やるべきこと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>)
}
}
別の(矢印)関数内で関数呼び出しをラップすることは不要であり、パラメーターを適切に転送しません(すべての中間矢印関数はパラメーターを受け入れないため)。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加