React Hook 父子元件相互呼叫方法
阿新 • • 發佈:2020-07-09
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