Call child method from parent

前端 未结 16 2340
长发绾君心
长发绾君心 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:27

    You can achieve this easily in this way

    Steps-

    1. Create a boolean variable in the state in the parent class. Update this when you want to call a function.
    2. Create a prop variable and assign the boolean variable.
    3. From the child component access that variable using props and execute the method you want by having an if condition.

      class Child extends Component {
         Method=()=>{
         --Your method body--
         }
         render() {
           return (
          //check whether the variable has been updated or not
            if(this.props.updateMethod){
              this.Method();
            }
           )
         }
      }
      
      class Parent extends Component {
      
      constructor(){
        this.state={
         callMethod:false
        }
      
      }
      render() {
         return (
      
           //update state according to your requirement
           this.setState({
              callMethod:true
           }}
           
          );
         }
      }
      

提交回复
热议问题