最終更新:2022-12-16 (金) 13:59:18 (497d)
React/Refのフォワーディング
Ref のフォワーディングを使うと、コンポーネントは任意の子コンポーネントの ref を自分自身の ref として公開できるようになります
https://ja.reactjs.org/docs/forwarding-refs.html
対応
メモ
- コンポーネントが ref を受け取って、それをさらに下層の子に渡せる(つまり、ref を転送できる)ようになる
React.forwardRef (forwardRef)
- 親コンポーネントから受け取ったrefを自分のrefとして指定する
const FancyButton = React.forwardRef((props, ref) => ( <button ref={ref} className="FancyButton"> {props.children} </button> )); // You can now get a ref directly to the DOM button: const ref = React.createRef(); <FancyButton ref={ref}>Click me!</FancyButton>;
- 第2引数のrefはReact.forwardRefの呼び出しを使ってコンポーネントを定義したときにだけ存在する
- 通常の関数またはクラスコンポーネントは ref 引数を受け取らず、ref は props からも利用できません。