APIリファレンス{/* SVGアイコン */}
レガシーReact API{/* SVGアイコン */}

createRef

落とし穴

createRefは、主にクラスコンポーネントで使用されます。関数コンポーネントは、通常はuseRefを代わりに使用します。

createRefは、任意の値を格納できるrefオブジェクトを作成します。

class MyInput extends Component {
inputRef = createRef();
// ...
}

リファレンス{/* SVGアイコン */}

createRef(){/* SVGアイコン */}

createRefを呼び出して、クラスコンポーネント内にrefを宣言します。

import { createRef, Component } from 'react';

class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...

以下の例をご覧ください。

パラメータ{/* SVGアイコン */}

createRefはパラメータを取りません。

戻り値{/* SVGアイコン */}

createRefは、単一のプロパティを持つオブジェクトを返します。

  • current: 最初はnullに設定されています。後で別の値に設定できます。 refオブジェクトをReactにJSXノードのref属性として渡すと、Reactはそのcurrentプロパティを設定します。

注意点{/* SVGアイコン */}

  • createRef は常に異なるオブジェクトを返します。これは、{ current: null } を自分で記述するのと同じです。
  • 関数コンポーネントでは、常に同じオブジェクトを返す useRef を代わりに使用するのが適切です。
  • const ref = useRef()const [ref, _] = useState(() => createRef(null)) と同等です。

使用方法 (リンクアイコンSVG)

クラスコンポーネントでのrefの宣言 (リンクアイコンSVG)

クラスコンポーネント 内でrefを宣言するには、createRef を呼び出し、その結果をクラスフィールドに代入します。

import { Component, createRef } from 'react';

class Form extends Component {
inputRef = createRef();

// ...
}

JSXで ref={this.inputRef}<input> に渡すと、Reactは this.inputRef.current にinput DOMノードを設定します。たとえば、入力にフォーカスするボタンを作成する方法は次のとおりです。

import { Component, createRef } from 'react';

export default class Form extends Component {
  inputRef = createRef();

  handleClick = () => {
    this.inputRef.current.focus();
  }

  render() {
    return (
      <>
        <input ref={this.inputRef} />
        <button onClick={this.handleClick}>
          Focus the input
        </button>
      </>
    );
  }
}

落とし穴

createRefは、主にクラスコンポーネントで使用されます。関数コンポーネントは、通常はuseRefを代わりに使用します。


代替案 (リンクアイコンSVG)

createRef を使用したクラスから useRef を使用した関数への移行 (リンクアイコンSVG)

新しいコードでは、クラスコンポーネント の代わりに関数コンポーネントを使用することをお勧めします。createRef を使用している既存のクラスコンポーネントがある場合は、次のように変換できます。元のコードは次のとおりです。

import { Component, createRef } from 'react';

export default class Form extends Component {
  inputRef = createRef();

  handleClick = () => {
    this.inputRef.current.focus();
  }

  render() {
    return (
      <>
        <input ref={this.inputRef} />
        <button onClick={this.handleClick}>
          Focus the input
        </button>
      </>
    );
  }
}

このコンポーネントをクラスから関数に変換する場合は、createRef の呼び出しを useRef の呼び出しに置き換えます。

import { useRef } from 'react';

export default function Form() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>
        Focus the input
      </button>
    </>
  );
}