はじめに
最近、Reactのクラスコンポーネントの書き方も色々あると知ったので備忘として残しておきます。
同じ内容だけど違う書き方のクラスコンポーネント
いつものReactの書き方
constructorが書いてあってなんだか安心します。
関数のbindもしてますね。
class App extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
this.incrementCounter = this.incrementCounter.bind(this);
}
incrementCounter() {
this.setState({
counter: this.state.counter + 1
});
}
render() {
…
}
}
export default App;
いつもと違うReactの書き方
え!?constructorが書いてないじゃん!
constructorは最初に呪文のように書けって習ったよ!?
関数のbindもしてないじゃん!
import React, {Component} from 'react';
class App extends Component {
state = {
counter: 0
};
incrementCounter = () => {
this.setState({
counter: this.state.counter + 1
});
}
render() {
...
}
}
export default App;
なぜ動く??
それでは、なぜ動くのでしょうか?
create-react-appが、既にBabelに設定をしてくれているためだそうです。
https://medium.com/@damianperaltam/using-class-instance-properties-in-react-with-create-react-app-and-babel-4ac4da5299e