Reactの参照のためのガイド
React.jsを使用する場合、DOM要素と直接対話する命令型コードを記述するためにエスケープハッチが必要になることがあります。 ReactのcreateRefメソッドを使用すると、まさにそれが可能になります。
Reactは、React.createRef()
を使用してDOMノードへの参照を取得する方法を提供します。 これは、実際には、この非常に馴染みのあるJavaScriptのスニペットと同等です。
document.getElementById('foo-id');
これはReact.createRef()
が行うこととまったく同じですが、少し異なる設定が必要です。
使用法
DOMノードへの参照を取得するには、次の2つのことを行う必要があります。
import React, { Component } from 'react'; class Foobar extends Component { constructor(props) { super(props); this.myInput = React.createRef(); // initialize "this.myInput" } render() { return ( <input ref={this.myInput}/> {/* pass "this.myInput" as prop */} ); } }
Reactのすべての標準HTML要素には、ref
と呼ばれる予約済みの小道具があります(予約済みの小道具であるstyle
とよく似ています)。 コンストラクターで初期化した参照をref
プロップに渡すだけです…そして出来上がり! this.myInput.current
を使用して、<input>
DOMノードとの対話を開始できます。
this.myInput.current
はDOMノードへの参照を保持します
例:フォーカシング
最後のコードスニペットを使用して、<input>
DOMノードとの対話を開始する方法を示すために少し調整してみましょう。
import React, { Component } from 'react'; export default class App extends Component { constructor(props) { super(props); this.myInput = React.createRef(); } render() { return ( <div> <input ref={this.myInput}/> <button onClick={() => { this.myInput.current.focus(); }}> focus! </button> </div> ); } }
focus()
メソッドの呼び出しは、React.jsのことではありません…通常のJavaScriptのことです! 💃🏻💃🏻たとえば、これはバニラJavaScriptで行われる方法です:
document.getElementById('myInput').focus();
HTMLメディア要素の制御
React.createRef()
と標準のJavaScript<video>
APIを使用して、再生を制御することもできます。
import React, { Component } from 'react'; export default class App extends Component { constructor(props) { super(props); this.myVideo = React.createRef(); } render() { return ( <div> <video ref={this.myVideo} width="320" height="176" controls> <source src="https://blender.com/big-buck-bunny.mp4" type="video/mp4" /> </video> <div> <button onClick={() => { this.myVideo.current.play(); }}> Play </button> <button onClick={() => { this.myVideo.current.pause(); }}> Pause </button> </div> </div> ); } }
useRefを使用したReactフック付きの参照
React Hooksの参照は、class
コンポーネントと大差ありません。 これは、useRefフックを使用して実現されます。 this
を省略することを忘れないでください、そうすればあなたは黄金になります🙌
import React, { useRef } from "react"; function App() { const myInput = useRef(null); return ( <div> <input ref={myInput}/> <button onClick={() => { myInput.current.focus(); }}> focus! </button> </div> ); }
使用できませんcreateRef
状態やライフサイクルコンポーネントなどのReact-y機能の多くが欠けているため、純粋関数コンポーネントの場合
✈️createRef()
の詳細については、Reactドキュメントにアクセスしてください。