Call child method from parent

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

    We can use refs in another way as-

    We are going to create a Parent element, it will render a <Child/> component. As you can see, the component that will be rendered, you need to add the ref attribute and provide a name for it.
    Then, the triggerChildAlert function, located in the parent class will access the refs property of the this context (when the triggerChildAlert function is triggered will access the child reference and it will has all the functions of the child element).

    class Parent extends React.Component {
        triggerChildAlert(){
            this.refs.child.callChildMethod();
            // to get child parent returned  value-
            // this.value = this.refs.child.callChildMethod();
            // alert('Returned value- '+this.value);
        }
    
        render() {
            return (
                <div>
                    {/* Note that you need to give a value to the ref parameter, in this case child*/}
                    <Child ref="child" />
                    <button onClick={this.triggerChildAlert}>Click</button>
                </div>
            );
        }
    }  
    

    Now, the child component, as theoretically designed previously, will look like:

    class Child extends React.Component {
        callChildMethod() {
            alert('Hello World');
            // to return some value
            // return this.state.someValue;
        }
    
        render() {
            return (
                <h1>Hello</h1>
            );
        }
    }
    

    Here is the source code-
    Hope will help you !

    0 讨论(0)
  • 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 (<Child request={request} onRequestHandled={()->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();
    }
    
    0 讨论(0)
  • 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
           }}
           <Child updateMethod={this.state.callMethod}></Child>
          );
         }
      }
      
    0 讨论(0)
  • 2020-11-21 23:27

    Here's a bug? to look out for: I concur with rossipedia's solution using forwardRef, useRef, useImperativeHandle

    There's some misinformation online that says refs can only be created from React Class components, but you can indeed use Function Components if you use the aforementioned hooks above. A note, the hooks only worked for me after I changed the file to not use withRouter() when exporting the component. I.e. a change from

    export default withRouter(TableConfig);
    

    to instead be

    export default TableConfig;
    

    In hindsight the withRouter() is not needed for such a component anyway, but usually it doesn't hurt anything having it in. My use case is that I created a component to create a Table to handle the viewing and editing of config values, and I wanted to be able to tell this Child component to reset it's state values whenever the Parent form's Reset button was hit. UseRef() wouldn't properly get the ref or ref.current (kept on getting null) until I removed withRouter() from the file containing my child component TableConfig

    0 讨论(0)
提交回复
热议问题