Function transfer with parameters through supports on reactions

I have a function that comes from the parent, down to the child of the child in the component hierarchy. This is usually not a big deal, but I need to get the parameter from the child. I am currently getting this error message: Unavailable (in promise) TypeError: this.props.myFunction is not a function.

Here is a sample code for what I am 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>) } } 

So, just for this: I pass myFunction as a support from SomeComponent up to ChildComponent2, in which I want it to be called whenever the button is pressed and the parameters are passed from ChildComponent2.

Thanks!

+15
source share
2 answers

I don’t understand why you will get this error, but you should do 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>) } } 

The wrapper of a function call inside another (arrow) function is simply not needed and will not redirect the parameter properly (since all your intermediate arrow functions do not accept the parameter).

+30
source

An alternative and IMO cleaner way to do this would be:

 class SomeComponent extends Component{ myFunction = param => { console.log('do something: ', param); } render(){ return ( <div> <ChildComponent1 onClick={this.myFunction}/> </div>) } } class ChildComponent1{ render(){ return (<div><ChildComponent2 onClick={this.props.onClick}/></div>) } } class ChildComponent2{ render(){ const { onClick } = this.props // destructure return (<Button onClick={()=>onClick(param)}>SomeButton</Button>) } } 
+2
source

Source: https://habr.com/ru/post/1262000/


All Articles