2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React ref初心者の覚書

Last updated at Posted at 2020-07-29

初心者がrefがよくわからなかったのでメモしています。

ref のフォワーディングの記事メモ

  • ref のフォワーディングはあるコンポーネントを通じてその子コンポーネントのひとつに ref を自動的に渡すテクニック

  • ref のフォワーディングはオプトインの機能であり、それにより、コンポーネントが ref を受け取って、それをさらに下層の子に渡せる(つまり、ref を “フォワーディング” できる)ようになります。

下の例では、FancyButton は渡された ref を取得して、それをレンダーする button DOM にフォワーディングするために、React.forwardRef を使っています。

ref.js
const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
  • フォアード
    転送
    意味は「特定の〜にやってきたデータを別の〜に向かって送り出してやること」です。

ReactのRefsを正しく取り扱うの記事メモ

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

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

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

これで何となくイメージだけ、、
下記の本家で詳しい説明があった。

Ref と DOMからのメモ


class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

Ref へのアクセス

  • ref が render メソッドの要素に渡されると、そのノードへの参照は ref の current 属性でアクセスできる。
  • ref の値はノードの種類によって異なります。
  • HTML 要素に対して ref 属性が使用されている場合、React.createRef() を使ってコンストラクタ内で作成された ref は、その current プロパティとして根底にある DOM 要素を受け取る
  • ref 属性がカスタムクラスコンポーネントで使用されるとき、ref オブジェクトはコンポーネントのマウントされたインスタンスを current として受け取ります
    関数コンポーネント (function components) には ref 属性を使用してはいけません。なぜなら、関数コンポーネントはインスタンスを持たない

まだ把握しきれない、、

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>
    );
  }
}
2
3
0

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?