LoginSignup
96
67

More than 3 years have passed since last update.

ReactのRefsを正しく取り扱う

Last updated at Posted at 2018-11-13

Reactで同一コンポーネント内でDOMの操作を行いたい場合、ref属性を使って参照をするという方法があります。しかしこれを扱う場合には注意が必要なので、備忘録として残しておきます。

Refsを使うべきシチュエーション

そもそも、Refsはあまり多用すべきでないと公式でアナウンスされています。というのもReactでは、親コンポーネントから子プロセスへの一方向データフローを原則としていて、Refsを使ってコンポーネントに作用をすると、その原則が崩れてしまうためです。

Refsを使って良い例は

  • テキストの選択、フォームへのフォーカスもしくはメディア(動画、音声)の再生の制御
  • アニメーションを発火させる場合
  • サードパーティのDOMコンポーネントを組み込む場合

と公式のドキュメントに記載されています。
JQueryのDOM操作的なことをしたい場合に例外的に使うイメージですかね。

Refsの使い方

Refsを扱うには3つ方法があります。

  • React.createRefメソッドを用いる(v16.3.0以上で利用可能)
  • refコールバック属性を用いる
  • ref文字列属性を用いる(非推奨 v17で削除)

3番目は非推奨なので省力します。

React.createRef メソッドを用いる

Reactがv16.3.0以上の場合、この方法で対処するのがベターです。

Example.jsx
import React, { Component } from 'react';

class Example extends Component {
    constructor(props) {
        super(props);
        this.hugaRef = React.createRef();
    }
    render() {
        return (    
            <input 
                className="_hoge"
                type="text"
                ref={this.hugaRef}
            />
        )
    }
    componentDidMount() {
        this.hugaRef.current.focus();
    }
};

export default Example;

refsはthis.hogeRef.currentで取得できます。

refコールバック属性を用いる

現時点でバージョンが16.2.0以下で、当分バージョンアップの予定がないのであれば、コールバック関数でDOMをセットしています。

Example.jsx
import React, { Component } from 'react';

class Example extends Component {
    constructor(props) {
        super(props);
        this.hugaRef = null;
        this.setHugaRef = element => {
            this.hugaRef = element;
       }
    }
    render() {
        return (    
            <input 
                className="_hoge"
                type="text"
                ref={this.setHugaRef}
            />
        )
    }
    componentDidMount() {
        this.hugaRef.focus();
    }
};

export default Example;

出典

Refs and the DOM - React

96
67
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
96
67