1.子組件調用父組件函數方法javascript
//父組件 let Father=()=>{ let getInfo=()=>{ } return ()=>{ <div> <Children getInfo={getInfo} /> </div> } }
//子組件 let Children=(param)=>{ return ()=>{ <div> <span onClick={param.getInfo}>調用父組件函數</span> </div> } }
子組件調用父組件函數,能夠向父組件傳參,刷新父組件信息html
2.父組件條用子組件函數方法java
//父組件 //須要引入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 使用,要不就會出現如下警告react
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函數