LoginSignup
15
6

More than 3 years have passed since last update.

React function compornent(FC)とclass compornentの違い

Last updated at Posted at 2020-01-14

新しく書き始める時にfunction compornent(FC)class compornentで書く違い、書き方を学んだので、memo。

React function compornent(FC)とclass compornentの違い

基本的にはfunction compornent(関数コンポーネント)で書いた方が推奨されている。

使い分けるポイントとしては…

FCは、簡潔に書くことができる
class compornentのrender部分だけで書いてる感じ。
デメリットは状態管理によるrender()制御ができない(制御できることといえば、propsを渡せることだけ)

class compornentは状態を管理したい時に使う
・ライフサイクルメソッドを適切に使うことにより、render() を制御することが可能。
・propsはもちろんstateも使うことができる

書き方の違い

  • function compornent(FC)
import React from "react";

const Test = () => {
  return (
    //処理
    <div>
      <h1>{'FCの書き方!'}</h1>
    </div>
  );
};
export default Test;
  • class compornent
import React from "react";

class Test2 extends React.Component {
  //なくてもよい
  constructor(props) {
    super(props);
    this.state = {count: 100}; // stateも使える
  }

  // render() メソッドは、クラスコンポーネントで必ず定義しなければならない唯一のメソッドなので必要
  render() {
    return (
      //処理
      <div>{'class compornentの書き方'}</div>
    );
  }
}

export default Test2;

使うときは、、、

import Test from "./FCTest.index"; 
import Test2 from "./ClassTest.index";

return (
    <Test /> 
    <Test2 /> //これで使える
;

参考
https://ja.reactjs.org/docs/react-component.html
https://teratail.com/questions/118890
https://www.sambaiz.net/article/225/

15
6
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
15
6