Reactガイドを読んでいくその144

これは

Reactのガイドを読んでいく記事です。

ガイドのリンク

ja.reactjs.org

React.forwardRef

refを配下ツリーの別コンポーネントに渡すReactコンポーネントを作成する。
これは以下のようなシナリオで役に立つ。
・Forwarding refs to DOM components
 DOM コンポーネントに ref をフォワーディングする
・Forwarding refs in higher-order-components
 高階コンポーネントにおける ref のフォワーディング

React.forwardRefはレンダー関数を引数として受け入れ、Reactはpropsとrefを2つの引数として呼び出す。
関数はReactノードを返す必要がある。

//この部分から
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>;

今日はここまで