Call child component method from parent component in reactjs

后端 未结 5 884
[愿得一人]
[愿得一人] 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 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 

    Child Component

    ; });

    Call the exposed function from the parent with the ref.

    const Parent = () => {
      const childRef = useRef();
    
      return (
        
    ); };

提交回复
热议问题