Reactの仮想DOMは、遭遇するほとんどの状況をエレガントに処理しますが、実際の要素と対話する必要がある場合もあります。 これらの機会のために、Reactはrefシステムを提供します。
参照の作成
参照の作成は非常に簡単です。 プロパティに割り当てるコールバックを渡すだけです。
class MyComponent extends Component {
render() {
return (
<div>
<input ref={input => this.myInput = input} />
</div>
);
}
}
そこから、経由でその要素にアクセスできます this.myInput
. これを使用する方法はいくつかあります。
参照を使用して入力の値を取得する
アクセスするのと同じくらい簡単です value
要素の。 まるで2005年のようです。
class MyComponent extends Component {
alertInput() {
const value = this.myInput.value;
// Please don't use alert in actual applications.
alert(value);
}
render() {
return (
<div>
<input ref={input => this.myInput = input} />
<button onClick={this.alertInput.bind(this)}>Alert</button>
</div>
);
}
}
Reduxを使用している場合は、おそらくこれに制御されたコンポーネントを使用することをお勧めします。 ただし、簡単なデモを知っておくと便利です。
設定 value
うまく終わらないでしょう。 Reactは、再レンダリング時に要素を消去します。
参照を使用して入力に焦点を合わせる
フォーカスの管理は、適切な代替手段がないという理由だけで、おそらくrefの最も一般的なユースケースの1つです。
class MyComponent extends Component {
// As soon as the component mounts, `myInput` will be focused.
componentDidMount() {
this.myInput.focus();
}
render() {
return (
<div>
<input ref={input => this.myInput = input} />
</div>
);
}
}
参照を使用してキャンバスを操作する
対話するキャンバス要素がない限り、キャンバスはあまり役に立ちません。
class MyComponent extends Component {
// The canvas is drawn when the component is mounted.
componentDidMount() {
this.drawCanvas();
}
// The canvas is drawn when the component updates.
componentDidUpdate() {
this.drawCanvas();
}
drawCanvas() {
const context = this.myCanvas.getContext('2d');
context.clearRect(0, 0, 500, 500);
context.fillText('If you can read this, your eyes are better than mine.', 250, 250);
}
render() {
return (
<div>
<canvas ref={canvas => this.myCanvas = canvas} height={500} width={500} />
</div>
);
}
}
更新時にキャンバスを再描画することを忘れないでください。