問題一覧に戻る
上級高度なパターンと型
問題96: useImperativeHandle

useImperativeHandleで親コンポーネントに公開されるref値をカスタマイズする方法を学びます。DOM要素を直接公開する代わりに、refにカスタムメソッドを作成します。これにより、カプセル化を維持しながら制御されたコンポーネントAPIを提供します。フォーカス管理、スクロール制御、フォーム検証APIに有用です。

import React, { useRef, forwardRef, useImperativeHandle } from 'react';

{/* カスタムハンドルインターフェース */}
interface InputHandle {
focus: () => void;
clear: () => void;
}

{/* forwardRefを使用したコンポーネント */}
const CustomInput = forwardRef<, { placeholder?: string }>((props, ref) => {
const inputRef = useRef<HTMLInputElement>(null);

{/* 命令的APIを定義 */}
(ref, () => ({
focus: () => inputRef.current?.focus(),
: () => {
if (inputRef.current) inputRef.current.value = '';
}
}));

return <input ref={} placeholder={props.placeholder} />;
});

function App() {
const inputRef = useRef<>(null);

return (
<div>
<CustomInput ref={inputRef} placeholder="Type here" />
<button onClick={() => inputRef.current?.()}>Focus</button>
<button onClick={() => inputRef.current?.clear()}>Clear</button>
</div>
);
}

export default App;