LoginSignup
8
5

More than 3 years have passed since last update.

React hooksで子コンポーネントの関数を実行する

Posted at

TL;DR

forwardRefuseImperativeHandleを使う

詳細

Componentを継承したコンポーネントを定義した場合はrefを渡してメソッドを実行できる。
React hooksを使ってるとFunctionComponentになるのでコンポーネントにメソッドというものがない。
forwardRefuseImperativeHandle を使う。

サンプル

import React, { useImperativeHandle, forwardRef, useRef } from "react";
import { render } from "react-dom";

interface ChildProps {
  text: string;
}
const ChildBase: React.RefForwardingComponent<any, ChildProps> = (
  { text },
  ref
) => {
  const test = () => {
    window.alert(text);
  };
  useImperativeHandle(ref, () => ({
    test
  }));

  return <span>{text}</span>;
};
const Child = forwardRef(ChildBase);

const Parent: React.FC = () => {
  const ref = useRef<any>();
  const handleClick = () => {
    ref.current && ref.current.test();
  };
  return (
    <div>
      <button onClick={handleClick}>Exec</button>
      <Child ref={ref} text="Hello" />
    </div>
  );
};

render(<Parent />, document.getElementById("root"));

anyのところはどうするのがいいのかわかってない。

8
5
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
8
5