実際、主な機能は、親コンポーネントが子コンポーネントのメソッドを使用したり、子コンポーネントを制御したり、親コンポーネントで子コンポーネントの関数をトリガーしたりできることです。
useImperativeHandle を使用する場合、サブコンポーネントの 2 番目のパラメーター 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>
}
//フォローアップは継続的に更新されます。最近記録するために使用してください