LoginSignup
1
3

More than 5 years have passed since last update.

Componentのconstructor内のsuper(props)

Posted at

タイトルの通り、super(props)についてです。
Reactのコンポネントをclassを用いて書く際、以下のように記述することが多いと思います。

hoge.js
class Hoge extends React.Component {
  constructor(props) {
    super(props)
    .......
  }
 render() {
    return(
      <div>{this.props.name}</div>
    )
  }
}

ReactDOM.render(
  <Hoge name="hogehoge" />,
  document.getElementById("root")
)

ここでsuper(props)はReact.Componentのconstructorを継承しています。
React.Componentのconstructorで行っていることの中で、個人的に最も重要だと思われることは、classのpropsプロパティのセット(this.props = props)です。
これにより、class内でthis.propsの値が利用できます。

したがって以下のように、constructorの引数に違う変数を指定しても同様に動きます。

hogehoge.js
class Hoge extends React.Component {
 //propsの代わりにhogeを引数に指定
  constructor(hoge) {
    super(hoge)
    .......
  }
 render() {
    return(
      <div>{this.props.name}</div>
    )
  }
}

ReactDOM.render(
  <Hoge name="hogehoge" />,
  document.getElementById("root")
)

インスタンス化の際に以下の様になるだけです。
this.props = hoge

しかし、this.propsの値を取得するためにprops以外の値を指定することはできず、以下のようにするとエラーになります。

hogehoge.js
class Hoge extends React.Component {
  constructor(hoge) {
    super(hoge)
    .......
  }
 render() {
    return(
      //hogeというプロパティはないと言われます。
      <div>{this.hoge.name}</div> 
    )
  }
}

ReactDOM.render(
  <Hoge name="hogehoge" />,
  document.getElementById("root")
)
1
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
1
3