25
14

More than 5 years have passed since last update.

【React+TypeScript】React Hooks useImperativeHandleのサンプル

Posted at

React+TypeScript.png

TypeScriptでのuseImperativeHandleの使い方のサンプル。

親のコンポーネントから、子で定義したメソッドを呼び出す場合に使用します。

FancyInput.tsx
import React, { useRef, useImperativeHandle, forwardRef } from "react";

// 公開したいメソッドの定義
interface Handler {
  setFocus(): void;
}

// 公開したいメソッドを持つコンポーネントの定義
// プロパティを追加する場合は、forwardRef<Handler, Props>と定義する。
const FancyInput = forwardRef<Handler>((props, ref) => {
  const inputRef = useRef({} as HTMLInputElement);

  useImperativeHandle(ref, () => {
    return {
      setFocus() {
        inputRef.current.focus();
      }
    };
  });

  return <input ref={inputRef} type="text" />;
});

// コンポーネントの使い方
const App = () => {
  const ref = useRef({} as Handler);
  return (
    <>
      <FancyInput ref={ref} />
      <button
        onClick={() => {
          ref.current.setFocus();
        }}
      >
        click
      </button>
    </>
  );
};
25
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
14