1.子组件调用父组件函数方法
//父组件 let Father=()=>{ let getInfo=()=>{ } return ()=>{ <div> <Children getInfo={getInfo} /> </div> } }
//子组件 let Children=(param)=>{ return ()=>{ <div> <span onClick={param.getInfo}>调用父组件函数</span> </div> } }
子组件调用父组件函数,可以向父组件传参,刷新父组件信息
2.父组件条用子组件函数方法
//父组件 //需要引入useRef import {useRef} from 'react' let Father=()=>{ const childRef=useRef(); let onClick=()=>{ childRef.current.getInfo(); } return ()=>{ <div> <Children ref={childRef} /> <span onClick={onClick}>调用子组件函数</span> </div> } }
//子组件 //需要引入useImperativeHandle,forwardRef import {useImperativeHandle,forwardRef} from 'react' let Children=(ref)=>{ useImperativeHandle(ref, () => ({ getInfo:()=>{ //需要处理的数据 } })) return ()=>{ <div></div> } } Children = forwardRef(Children);
useImperativeHandle 需要配合着 forwardRef 使用,要不就会出现以下警告
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
参考:https://www.cnblogs.com/shine1234/p/13223391.html