LoginSignup
0
0

More than 3 years have passed since last update.

Reactのthis.props.fooなんて知らないぞ!

Posted at

結論

コンポーネントに渡された入力データを this.props で参照し、render() の中で使用する。

内容

完全React初心者の自分が、練習がてらコンポーネントを自作する際に、メソッドの中でthis.props.hogeが使用されているのを見かけ、「なんだこれは、こんなの定義してないのぞ。。。。。」と思ってみたので調べてまとめてみた。

まずは以下のコードを見て欲しい。

class HelloMessage extends React.Component {
  render() {
    return (
      <div>
        Hello {this.props.name}
      </div>
    );
  }
}

ReactDOM.render(
  <HelloMessage name="Taylor" />,
  document.getElementById('hello-example')
);

これはとても初歩的な自作Reactコンポーネント。ちなみにこちらは、参考資料に掲載している本家Reactのホームページのチュートリアルから抜粋してきたものである。

  <HelloMessage name="Taylor" />

コンポーネントを使用する際、name="Taylor"をコンポーネントに渡している。this.props.nameはこのnameを参照して、コンポーネントの中で Hello {this.props.name}を表示する。


参考資料
React tutorial

0
0
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
0
0