createRef
createRef は任意の値を保持できる ref オブジェクトを作成します。
class MyInput extends Component {
inputRef = createRef();
// ...
}リファレンス
createRef()
createRef を呼び出して、クラスコンポーネント内で ref を宣言します。
import { createRef, Component } from 'react';
class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...引数
createRef は引数を取りません。
返り値
createRef は単一のプロパティを持つオブジェクトを返します。
current:nullに初期化されています。後で他の値にセットすることができます。JSX ノードのref属性として React に ref オブジェクトを渡すと、React はそのcurrentプロパティを適切にセットします。
注意点
createRefは常に異なるオブジェクトを返します。これは自分で{ current: null }を書くのと同等です。- 関数コンポーネントでは、同じオブジェクトを常に返す
useRefを代わりに使用することをお勧めします。 const ref = useRef()はconst [ref, _] = useState(() => createRef(null))と同等です。
使用法
クラスコンポーネントで ref を宣言する
クラスコンポーネント内で ref を宣言するには、createRef を呼び出し、その結果をクラスフィールドに割り当てます。
import { Component, createRef } from 'react';
class Form extends Component {
inputRef = createRef();
// ...
}これで JSX の <input> に ref={this.inputRef} を渡すと、React は this.inputRef.current を input の DOM ノードにセットします。例えば以下のようにして、input をフォーカスするボタンを作ることができます。
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 を使った関数への移行
新しいコードではクラスコンポーネントの代わりに関数コンポーネントの使用を推奨します。以下に、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> </> ); }