LoginSignup
28
23

More than 5 years have passed since last update.

React.createClassとReact.Componentの違い

Posted at

Reactでコンポーネントを作る際に表題の2つの方法があるわけなのですが、学習を始めた段階で違いがわかっていなかったので整理。

ES6を使うかどうか

一番の違いはここになります。

React.Component is the base class for React components when they are defined using ES6 classes.
//...
If you don't use ES6 yet, you may use the React.createClass() helper instead to create a component class.

ReactやReactNativeのチュートリアルではES6の記法に沿っているので、 React.Component が使われています。また基本的にはES6に移行するため、React.Componentを利用することが推奨されます。

mixinsのサポート有無

React.Componentではmixinがサポートされていません。ES6自体でmixinがサポートされていないからです。ただし ES6 においてもmixinのユースケースは代替できるとのこと。

Auto-bindingやgetInitializerなど一部メソッドの違い

React.createClassであった初期化メソッドの getInitializer はReact.Componentでは constructor で初期化されます。またイベントハンドラーなどはReact.createClassではauto-bindingが適用されますが、React.Componentでは明示的に bindingしてあげる必要があります。

constructor() {
  super();
  this.state = {dispText: 'input'};
  this.handleInput = this.handleInput.bind(this);
}

handleInput(event) {
  console.log(this.state.dispText);
  this.setState({dispText: event.target.value});
}

結論

基本的にはES6記法かどうかの違いで、React.Componentで代替可能であり、またES6記法の方がフレキシブルにコンポーネントを書けるので、React.Componentを使うほうがよいようです。

28
23
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
28
23