The child component calls the parent component function method

/ / parent component let Father () = = > {let getInfo () = = > {} return () = > {< div > < Children getInfo = {getInfo} / > < / div >}} / / let the child component Children=(param)=>{return ()=>{<div> <span onClick={param.getinfo}> call parent component function </span> </div>}} Refresh information about the parent componentCopy the code

The parent component calls the child component function method

UseRef import {useRef} from 'react' let Father=()=>{const childRef=useRef(); let onClick=()=>{ childRef.current.getInfo(); } return ()=>{<div> <Children ref={childRef} /> <span onClick={onClick}> Calls the child component function </span> </div>}} // child component / / need to introduce useImperativeHandle, forwardRef import {useImperativeHandle, forwardRef} from 'react' let Children = (ref) = > { useImperativeHandle(ref, () = > ({getInfo () = > {/ / need to handle data}})) return () = > {< div > < / div >}} Children = forwardRef (Children);Copy the code

UseImperativeHandle needs to be used in conjunction with the forwardRef or the following warning will appear

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

How does the react function component parent call child component methods