原文:React Hooks-Calling Child Component Function From Parent Component

 

In this article we’re are assuming that you are somewhat familiar with React Hooks

React.useImperativeHandlehooks from React. Now let us know briefly about these two. What are they? How are they used? And the most important question, how are we going to use them? So let’s get started!

ref attribute, which it receives, to another component below in the tree. So, in simple words forwardRef creates such a component which receives a ref attribute from its parent component and forwards it to the components down in the hierarchy.

 

Arguments and return type: React calls this function with two arguments one is props and the other is ref. This returns a react node something like this.

React 调用子组件的函数(函数)

 

 

React.useImperativeHandle

Cannot add property current, object is not extensible.

useImperativeHandle(ref,
() => {
focus: () => {// function name
// the above func. is customized function as it can
// behave differently than its normal behavior
}
});

 

Demo: Calling child function from parent in React Hooks

React 调用子组件的函数(函数)

 

 

 

So let us create a parent component first
So we have created a component with a button to call the child function later on.

 

 

 

Now, lets create a child component using forwardRef .
A child component is ready along with a function in which it alerts a message “Child function called”, this function is named as showAlert with no arguments, using useImperativeHandle as we have discussed above about the useImperativeHandle and the forwardRef hooks in React.

            }
}),
)
return (
<div>Child Component</div>
)
})

Our output is still the same because the child component is not rendered yet.

 

 

React.useRefwith that the showAlert() function will be called.

            }
}),
)
return (
<div>Child Component</div>
)
})

childRef.current.showAlert();

React 调用子组件的函数(函数)

 

 

Conclusion

current property of ref, which can be used anywhere in the component.

 

 

相关文章: