useImperativeHandle
親のコンポーネントから、子で定義したメソッドを呼び出すために使う
ユースケース例
親から子の input を .focus() したい
外部からモーダルの open() メソッドを呼びたい
カスタムコンポーネントに対して imperatively な制御が必要
実例:input に focus を当てる
code:子(tsx)
import { useRef, forwardRef, useImperativeHandle } from 'react';
type InputHandle = {
focus: () => void;
getValue: () => string | undefined;
};
const Input = forwardRef<InputHandle, {}>((_, ref) => {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current?.focus();
},
getValue: () => inputRef.current?.value,
}));
return <input ref={inputRef} />;
});
code:親(tsx)
export default function Parent() {
const inputRef = useRef<InputHandle>(null);
return (
<div>
<Input ref={inputRef} />
<button onClick={() => inputRef.current?.focus()}>Focus input</button>
<button onClick={() => console.log(inputRef.current?.getValue())}>Log value</button>
</div>
);
}