React.jsを使用する場合、DOM要素と直接対話する命令型コードを記述するためにエスケープハッチが必要になることがあります。 ReactのcreateRefメソッドを使用すると、まさにそれが可能になります。
Reactは、を使用してDOMノードへの参照を取得する方法を提供します React.createRef()
. これは、実際には、この非常に馴染みのある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
小道具…そして出来上がり! あなたはとの相互作用を開始することができます <input>
使用するDOMノード this.myInput.current
!
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フックの参照はそれほど違いはありません 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機能の多くが欠けているため、純粋関数コンポーネントの場合
✈️詳細については、 Reactdocsにアクセスしてください。 createRef()
.