Call child component method from parent component in reactjs

后端 未结 5 885
[愿得一人]
[愿得一人] 2021-02-10 01:41

I have requirement to call child component method from parent component in reactjs. I have tried using refs but not able to do it. Can anyone please suggest any solution. Than

相关标签:
5条回答
  • 2021-02-10 01:58

    You can pass registerCallback props to your child and call it from componentDidMount and pass reference to your child component method, then you can call it method at anytime

    0 讨论(0)
  • 2021-02-10 02:16

    If using React Hooks, you can make use of useRef and useImperativeHandle hooks.

    In the child component, add the functions in the hook.

    const Child = forwardRef((props, ref) => {
    
      const printSomething = () =>{
         console.log('printing from child function')
      }
      useImperativeHandle(ref, () => ({
        printSomething: printSomething
      }));
    
      return <h1>Child Component</h1>;
    });
    

    Call the exposed function from the parent with the ref.

    const Parent = () => {
      const childRef = useRef();
    
      return (
        <div>
          <Child ref={childRef} />
          <button onClick={() => childRef.current.printSomething()}>Click</button>
        </div>
      );
    };
    
    0 讨论(0)
  • 2021-02-10 02:17

    Don't :)

    Hoist the function to the parent and pass data down as props. You can pass the same function down, in case the child needs to call it also.

    https://facebook.github.io/react/docs/lifting-state-up.html

    0 讨论(0)
  • 2021-02-10 02:20

    You can assign a ref to the child component and then call the function form parent like

    class Parent extends React.Component {
       callChildFunction = () => {
           this.child.handleActionParent();  ///calling a child function here
      } 
       render(){
          return (
               <div>
               {/* other things */}
               <Child ref={(cd) => this.child = cd}/>
               </div>
          )
        }
    }
    
    class Child extends React.Component {
       handleActionParent = () => {
           console.log('called from parent')
       }
       render() {
          return (
               {/*...*/}
          )
       }
    }
    
    0 讨论(0)
  • 2021-02-10 02:22

    in your parent you can create a reference

    in the constructor:

     this.child = React.createRef();
    

    in any function:

    execute=(comment)=>{
            this.child.current.addComment();
        }
    
    render(){
            return (
                <div>
                    <Messages ref={this.child} comment={this.state.comment}/>
                </div>
            )
        }
    

    and in the Message(child) component

    addComment=()=>{
        console.log("Pi ", this.props);
    
      };
    
    0 讨论(0)
提交回复
热议问题