其实主要作用就是父组件可以使用子组件的方法 或者控制子组件,可以在父组件中触发子组件功能
当使用useImperativeHandle时,需要子组件中的第二个参数ref当作useImperativeHandle的第一个参数
forwardRef其实本质是一个高阶组件,用来传递Ref
//父组件
//forwardRef类其实算高阶组件
const ChildInput = forwardRef(ChildrenComponent);
function App = ()=>{
const inputRef = useRef(null);
useEffect(()=>{
inputRef.current.focus()
},[])
return (
<div><ChildInput ref={inputRef}/></div>
)
}
//子组件
function ChildrenComponent(props,ref){
const inputRef = useRef(null);
useImperativeHandle(ref,()=>inputRef.current);
return <input type='text' name='child input' ref={inputRef}></input>
}
//后续会继续更新 只是最近用到了 记录一下