React Refs

React は非常に特別な属性をサポートしていますRefこの属性は、render() が出力する任意のコンポーネントにバインドするために使用できます。

この特別な属性を使用すると、render() が返す対応するバッキングインスタンスを参照できるため、常に正しいインスタンスを取得できます。

React では、Refs(参照)は DOM 要素やコンポーネントインスタンスにアクセスする方法を提供します。Refs を使用すると、DOM 要素を直接操作したり、子コンポーネントのインスタンスを取得したりできます。フォーカスの処理、テキスト選択、メディア再生、強制アニメーションのトリガー、サードパーティ製 DOM ライブラリの統合などのシナリオに適しています。

使用方法

React.createRef または useRef を使用して refs を作成およびアクセスします。

React.createRef は通常クラスコンポーネントで使用され、useRef はフックであり、通常は関数コンポーネントで使用されます。

さらに、イベントハンドラで this をバインドする場合、クラスプロパティ構文を使用することで、レンダリングのたびに新しい関数を作成することを避けられます。

  • Ref の作成: クラスコンポーネントのコンストラクタでReact.createRefref オブジェクトを作成し、それをコンポーネントインスタンスのプロパティに割り当てます。
  • Ref のバインド:renderメソッド内で、ref オブジェクトを参照したい DOM 要素にバインドします。
  • Ref へのアクセス: コンポーネントの他のメソッドで、this.myInputRef.currentバインドされた DOM 要素にアクセスし、その要素のプロパティとメソッドを操作できます。

完全な例

this を使用して現在の React コンポーネントを取得したり、ref を使用してコンポーネントの参照を取得できます。例は次のとおりです。

React の例

class MyComponent extends React.Component { constructor(props) { super(props); this.myInputRef = React.createRef(); } handleClick = () => { //ネイティブ DOM API を使用してフォーカスを取得 this.myInputRef.current.focus(); } render() { return ( <div> <input type="text" ref={this.myInputRef} /> <input type="button" value="クリックすると入力欄にフォーカスします" onClick={this.handleClick} /> </div> ); } }

試してみる »

この例では、入力欄のバッキングインスタンスの参照を取得し、ボタンをクリックすると入力欄にフォーカスが当たります。

getDOMNode() メソッドを使用して DOM 要素を取得することもできます。


Refs の作成

React は refs を作成するための React.createRef メソッドを提供します。

例

import React from 'react';
import ReactDOM from 'react-dom';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  componentDidMount() {
    this.myRef.current.focus();
  }

  render() {
    return <input type="text" ref={this.myRef} />;
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
// MyComponent コンポーネントをレンダリング
root.render(<MyComponent />);

コールバック Refs

refs を作成するもう 1 つの方法は、コールバック関数を使用することです。この方法は React 16.3 より前では一般的でしたが、現在は React.createRef を使用することが推奨されています。

例

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.setMyRef = element => {
      this.myRef = element;
    };
  }

  componentDidMount() {
    if (this.myRef) {
      this.myRef.focus();
    }
  }

  render() {
    return <input type="text" ref={this.setMyRef} />;
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
// MyComponent コンポーネントをレンダリング
root.render(<MyComponent />);

Refs を使用した DOM 要素へのアクセス

Refs を使用すると、DOM 要素に直接アクセスして操作できます。

例

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  handleClick = () => {
    this.myRef.current.style.backgroundColor = 'yellow';
  };

  render() {
    return (
      <div>
        <input type="text" ref={this.myRef} />
        <button onClick={this.handleClick}>Change Background</button>
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
// MyComponent コンポーネントをレンダリング
root.render(<MyComponent />);

Refs を使用した子コンポーネントインスタンスへのアクセス

Refs は、子コンポーネントのインスタンスメソッドやプロパティにアクセスするためにも使用できます。

例

class ChildComponent extends React.Component {
  focusInput = () => {
    this.inputRef.current.focus();
  };

  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  render() {
    return <input type="text" ref={this.inputRef} />;
  }
}

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
  }

  handleClick = () => {
    this.childRef.current.focusInput();
  };

  render() {
    return (
      <div>
        <ChildComponent ref={this.childRef} />
        <button onClick={this.handleClick}>Focus Child Input</button>
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
// MyComponent コンポーネントをレンダリング
root.render(<MyComponent />);

useRef Hook の使用(関数コンポーネント)

関数コンポーネントでは、useRef Hook を使用して refs を作成できます。

例

import React, { useRef } from 'react';
import ReactDOM from 'react-dom';

const MyComponent = () => {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
// MyComponent コンポーネントをレンダリング
root.render(<MyComponent />);

まとめ

  • Refs の作成: クラスコンポーネントではReact.createRef、関数コンポーネントではuseRef Hook。
  • DOM 要素へのアクセス: refs を使用して DOM 要素に直接アクセスし操作します。
  • 子コンポーネントインスタンスへのアクセス: refs を使用して子コンポーネントのインスタンスメソッドまたはプロパティにアクセスします。
  • 公開するインスタンス値のカスタマイズ:useImperativeHandleとforwardRef子コンポーネントが親コンポーネントに公開するインスタンス値をカスタマイズします。
  • 並列モードでの Refs: Refs は並列モードでも正常に機能し、useTransitionなどの並列モード関連の Hook と組み合わせて使用できます。
その他の拡張