APIリファレンス{/* SVGアイコン */}
レガシーReact API{/* SVGアイコン */}
createRef
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> </> ); } }
代替案 (リンクアイコン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> </> ); } }
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> </> ); }