Reactガイドを読んでいくその90
これは
Reactのガイドを読んでいく記事です。
ガイドのリンク
RefとDOM
DOM 要素への Ref の追加
DOMノードへの参照を保持するためにrefを使っている例
コンポーネントがマウントされるとReactはcurrentプロパティにDOM要素を割り当ててマウントが解除されるとnullに戻す。
refの更新はcomponentDidMountか、componentDidUpdateライフサイクルメソッドの前に行われる。
class CustomTextInput extends React.Component { constructor(props) { super(props); // textInput DOM 要素を保持するための ref を作成します。 this.textInput = React.createRef(); this.focusTextInput = this.focusTextInput.bind(this); } focusTextInput() { // 生の DOM API を使用して明示的にテキストの入力にフォーカスします。 // 補足:DOM ノードを取得するために "current" にアクセスしています。 this.textInput.current.focus(); } render() { // コンストラクタで作成した `textInput` に <input> ref を関連付けることを // React に伝えます。 return ( <div> <input type="text" ref={this.textInput} /> <input type="button" value="Focus the text input" onClick={this.focusTextInput} /> </div> ); } }
今日はここまで。