Passing a function with parameters through props on reactjs

前端 未结 2 1523
青春惊慌失措
青春惊慌失措 2020-12-13 04:03

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

相关标签:
2条回答
  • 2020-12-13 04:52

    An alternative and IMO more clean way to do it would be like this:

    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>)
          }
    }
    
    0 讨论(0)
  • 2020-12-13 04:57

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

    0 讨论(0)
提交回复
热议问题