Home >Web Front-end >JS Tutorial >How Can I Call Child Methods from Parent Components in React?
In React, it's not always necessary to call child methods directly. However, there are instances where it might be necessary, such as when the child component exposes an imperative method. This article demonstrates how to achieve this using refs, both for class-based and functional components.
To call a child method from a parent class-based component using refs, follow these steps:
const childRef = React.createRef();
<Child ref={childRef} />
childRef.current.getAlert();
With the introduction of React Hooks, you can now use refs in functional components as well. Here's how to call a child method from a parent functional component using refs:
const childRef = useRef();
const Child = forwardRef((props, ref) => { // ... });
useImperativeHandle(ref, () => ({ getAlert() { alert('clicked'); } }));
childRef.current.getAlert();
Note: It's important to note that using refs to call child methods is generally discouraged in React. It's better practice to pass data down and events up through props and state.
The above is the detailed content of How Can I Call Child Methods from Parent Components in React?. For more information, please follow other related articles on the PHP Chinese website!