1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ReactのFunctionComponentについて

Last updated at Posted at 2020-04-20

ちゃんとReactを始めたのがv16からなんですが、最初に謎だったのがClassComponent」と比較された文章でした。調べてると3つあって、あまり賢くないので文章を読んでもよく違いが理解できず、、、

  • FunctionComponet(FC)
  • ClassComponent
  • SFC

v16以前のバージョンもやったことはあるのですが、既存の改修等でちゃんと理解できてない私には違いが分かりにくかったのでメモを残しておこうかと思います。違いが分からなくても組めたのですが、モヤモヤしたので。。。

今後、新規でコンポーネントを作成する場合はFCで組んでいけば良いみたいです。
もし勘違いして理解してたら教えてもらえるとありがたいですm(_ _)m

Function Component(FC)

  • v16から追加されたコンポーネント
  • SFCとは違ってStateが使えるようになった関数型コンポーネント

v16以前は下記のようにSFCとClassComponentを使い分けていた

  • 状態(state)を持つ必要がないコンポーネント:SFC
  • 状態(state)を保つ必要があるコンポーネント:ClassComponent

FCが出たことで関数型コンポーネントでも状態保持が可能になり、実質的な違いがなくなった。

const App: React.FC = () => {
  const [count, setCount] = useState(0)

  return (
    <div>
      <p>count : { count }</p>
      <button onClick={() => setCount(count + 1)}>increment</button>
    </div>
  )
}

Stateless Function Component(SFC)

名前のまま、stateを持たない関数型コンポーネント。
stateを持たないため状態を保持できない。
共通フッターなどを状態を持たないコンポーネントに使われる。

特徴

  • ライフサイクルメソッドを持たない
  • ref属性を設定できない
  • stateがない
const Counter: React.SFC = (props) => {
  // count値を保持できないため、propsでcount値をもらう
  let { count } = props
  return (
    <div>
      count : { count }
    </div>
  )
}

Class Component

Classとして定義されたコンポーネント。

特徴

  • ライフサイクルがある
  • stateがあるので状態を保持できる
class Counter extends React.Component {
  constructor(props) {
    super(props)
    this.state = { count: 0 }
  }

  render() {
    const { count } = this.state
    return (
     <div>
      <p>count : { count }</p>
      <button onClick={() => this.setState({ counter: count + 1 })}>increment</button>
    </div>
    )
  }
}
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?