LoginSignup
4
3

More than 5 years have passed since last update.

React コンポーネントで自分の子要素を取得するときのイディオム

Posted at

React コンポーネントで自分の子要素を取得するとき、Callback Refs を使っていた。v16.3 以降は、React v16.3.0: New lifecycles and context API によると、createRef API を使うのが普通なのかもしれない。

以下は、コンポーネントがマウントされたら、input タグにフォーカスをもってゆくコード。createRef 版はこう書く。

export default class Parent extends Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }
  componentDidMount() {
    this.inputRef.current.focus();
  }
  render() {
    return <input type="text" ref={this.inputRef} />;
  }
}

class Child extends Component {
  render() {
    return <div>{this.props.children}</div>
  }
}

Callback Refs だとこうだ。

export default class Parent extends Component {
  componentDidMount() {
    this.inputRef.focus();
  }
  render() {
    return <input type="text" ref={node => this.inputRef = node} />;
  }
}

Callback Refs でも、十分シンプルでイージーだと感じるのは私だけだろうか。「なるべく力の弱いものを使え!」という言葉を思い出した。この投稿で有用なのは最後の引用だけだ。

リファレンス

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