LoginSignup
0
0

More than 3 years have passed since last update.

【React③】Component

Last updated at Posted at 2020-10-22

Componentとは

ComponentはUIを作成するためにあり、見た目(View)機能(Controller)で成り立っている。
webの構造はComponentのツリー構造をしていて
headerのComponentのなかにnavigation、login のComponentが含まれる。
ReactではComponentを一個ずつ作ってWebアプリなどを構成する。

Componentのメリット

  • 再利用性
    • 一つのComponentを作ると引数(Props)を渡すことができる
    • 例:buttonというコンポネントからlogin、log-outボタンを作成できる
  • 分割管理
    • Component同士は疎結合なので、影響し合わない
  • 修正変更、新機能追加が簡単
    • 疎結合であることから、修正変更が必要なComponentのみ変更することができる

Componentの種類

  • Class Component:クラスによって定義されたComponent
    • React.Componentを継承
    • constructorでpropsを初期化
    • ライフサイクルやstateを持つ
      • webページが表示されるときに生成され、ユーザの操作や次のページへの遷移すると消える
    • propsにはthisが必要(このclass内のpropsを使うため)
    • render内でJSXをreturn
    • 最近推奨されてない
//App=Class Component

import React, { Component } from 'react';

class App extends Component{
    constructor(props){
        super(props);
    }
    render() {
        return(
            <div>
                <h2>{this.props.title}</h2>
            </div>
        );
    }
}
  • Functional Component:関数型で定義されたComponent
    • ES6のアロー関数で記述
    • stateを持たない
    • propsを引数に受け取ることができる 
    • JSXをreturnする
//App=Functional Component

import React from 'react';
//Functional Componentでは{Component}のimportは不要

const App = (props) =>{
    return (
        <div>
            <h2>{props.title}</h2>
        </div>
    );  
}
0
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
0
0