Call child method from parent

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

    Another way of triggering a child function from parent is to make use of the componentDidUpdate function in child Component. I pass a prop triggerChildFunc from Parent to Child, which initially is null. The value changes to a function when the button is clicked and Child notice that change in componentDidUpdate and calls its own internal function.

    Since prop triggerChildFunc changes to a function, we also get a callback to the Parent. If Parent don't need to know when the function is called the value triggerChildFunc could for example change from null to true instead.

    const { Component } = React;
    const { render } = ReactDOM;
    
    class Parent extends Component {
      state = {
        triggerFunc: null
      }
    
      render() {
        return (
          
    ); } } class Child extends Component { componentDidUpdate(prevProps) { if (this.props.triggerChildFunc !== prevProps.triggerChildFunc) { this.onParentTrigger(); } } onParentTrigger() { alert('parent triggered me'); // Let's call the passed variable from parent if it's a function if (this.props.triggerChildFunc && {}.toString.call(this.props.triggerChildFunc) === '[object Function]') { this.props.triggerChildFunc(); } } render() { return (

    Hello

    ); } } render( , document.getElementById('app') );
    
    
    

    CodePen: https://codepen.io/calsal/pen/NWPxbJv?editors=1010

提交回复
热议问题