Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>)
    }
}

So just to sum 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.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
226 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...