Call child method from parent

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

    I think that the most basic way to call methods is by setting a request on the child component. Then as soon as the child handles the request, it calls a callback method to reset the request.

    The reset mechanism is necessary to be able to send the same request multiple times after each other.

    In parent component

    In the render method of the parent:

    const { request } = this.state;
    return (resetRequest()}/>);
    

    The parent needs 2 methods, to communicate with its child in 2 directions.

    sendRequest() {
      const request = { param: "value" };
      this.setState({ request });
    }
    
    resetRequest() {
      const request = null;
      this.setState({ request });
    }
    

    In child component

    The child updates its internal state, copying the request from the props.

    constructor(props) {
      super(props);
      const { request } = props;
      this.state = { request };
    }
    
    static getDerivedStateFromProps(props, state) {
      const { request } = props;
      if (request !== state.request ) return { request };
      return null;
    }
    

    Then finally it handles the request, and sends the reset to the parent:

    componentDidMount() {
      const { request } = this.state;
      // todo handle request.
    
      const { onRequestHandled } = this.props;
      if (onRequestHandled != null) onRequestHandled();
    }
    

提交回复
热议问题