Call child method from parent

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

    If you are doing this simply because you want the Child to provide a re-usable trait to its parents, then you might consider doing that using render-props instead.

    That technique actually turns the structure upside down. The Child now wraps the parent, so I have renamed it to AlertTrait below. I kept the name Parent for continuity, although it is not really a parent now.

    // Use it like this:
    
      
    
    
    class AlertTrait extends Component {
      // You will need to bind this function, if it uses 'this'
      doAlert() {
        alert('clicked');
      }
      render() {
        return this.props.renderComponent({ doAlert: this.doAlert });
      }
    }
    
    class Parent extends Component {
      render() {
        return (
          
        );
      }
    }
    

    In this case, the AlertTrait provides one or more traits which it passes down as props to whatever component it was given in its renderComponent prop.

    The Parent receives doAlert as a prop, and can call it when needed.

    (For clarity, I called the prop renderComponent in the above example. But in the React docs linked above, they just call it render.)

    The Trait component can render stuff surrounding the Parent, in its render function, but it does not render anything inside the parent. Actually it could render things inside the Parent, if it passed another prop (e.g. renderChild) to the parent, which the parent could then use during its render method.

    This is somewhat different from what the OP asked for, but some people might end up here (like we did) because they wanted to create a reusable trait, and thought that a child component was a good way to do that.

提交回复
热议问题