Calling Child Methods from the Parent Component
In React, communication between components is typically achieved through props (properties) and events, but it is possible to access and invoke child component methods from the parent component using references.
Method Invocation Using Refs
Example with Hooks
const Child = forwardRef((props, ref) => { useImperativeHandle(ref, () => ({ getAlert() { alert("getAlert from Child"); } })); return <h1>Hi</h1>; }); const Parent = () => { const childRef = useRef(); return ( <div> <Child ref={childRef} /> <button onClick={() => childRef.current.getAlert()}>Click</button> </div> ); }; ReactDOM.render(<Parent />, document.getElementById('root'));
In this example, getAlert() is a method exposed by the Child component that can be invoked from the Parent component by accessing the current property of the childRef. Note that invoking child methods directly from the parent is not recommended and should be avoided in favor of proper component communication patterns.
The above is the detailed content of How Can I Call Child Component Methods from a Parent Component in React?. For more information, please follow other related articles on the PHP Chinese website!