Call child method from parent

前端 未结 16 2393
长发绾君心
长发绾君心 2020-11-21 22:23

I have two components.

  1. Parent component
  2. Child component

I was trying to call child\'s method from Parent, I tried this way but couldn\

16条回答
  •  广开言路
    2020-11-21 23:21

    I hope I'm not repeating anything from above but what about passing a callback prop that sets the function in the parent? This works and is pretty easy. (Added code is between the ////'s)

    class Parent extends Component {
      ///// 
      getAlert = () => {} // initial value for getAlert
    
      setGetAlertMethod = (newMethod) => {
        this.getAlert = newMethod;
      }
      /////
    
      render() {
        return (
          
            
          
          );
        }
      }
    
    
    
    class Child extends Component {
      /////
      componentDidMount() {
        this.props.setGetAlertMethod(this.getAlert);
      }
      /////
    
      getAlert() => {
        alert('clicked');
      }
    
      render() {
        return (
          

    Hello

    ); } }

提交回复
热议问题