LoginSignup
0
1

More than 3 years have passed since last update.

Reactでクラスフィールドを使用する(create-react-appとBabelを使用)

Posted at

はじめに

最近、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

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