現在Reactを勉強しています。
表題の通り、super(props)の役割がわかりません。
1つ自分が理解しているのは、以下の記事です。
https://qiita.com/hand-dot/items/61a4b808f110b12e4281
この記事には、super(props)を書かないと、constructor内において、this.propsに接続できないと書いてあり、そちらは理解しました。自分で動かしたりして納得しています。
自分が理解できていないのは、以下のような場合です。
class Counter extends React.Component { constructor(props){ super(props); this.handleAddOne = this.handleAddOne.bind(this) this.handleMinusOne = this.handleMinusOne.bind(this) this.handleReset = this.handleReset.bind(this) this.state = { count: 0 }; } handleAddOne(){ this.setState((prevState) => { return { count: prevState.count + 1 } }) } handleMinusOne(){ console.log("handleMinusOne") } handleReset(){ console.log("handleReset") } render(){ return ( <div> <h1>Count: {this.state.count}</h1> <button onClick={this.handleAddOne}>+1</button> <button onClick={this.handleMinusOne}>-1</button> <button onClick={this.handleReset}>reset</button> </div> ) } } ReactDOM.render(<Counter/>, document.getElementById('app'))
上記コードの場合、特にconstructor内でthis.propsに接続しているわけではありません(していないように見えます)。しかし、super(props)をコメントアウトすると、画面全体が消えてしまいます。
super(props)の役割は、constructor内でthis.propsに接続できるようにすることであると理解していた自分にとっては不可解でした。
ご存知の方はお教えください。
何卒よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/30 16:50
2019/05/30 23:22
2019/05/31 01:12