LoginSignup
13
9

More than 3 years have passed since last update.

Reactコンポーネントの基本

Posted at

コンポーネントの基本

コンポーネントとは?

UIは2つに分類される
1. 見た目(View)
2. 機能(Controller)

コンポーネント = 見た目 + 機能

Webページはコンポーネントのツリー構造になっている

なぜコンポーネントを使うのか

  • 再利用性するため
  • 分割統治するため
  • 変更に強くするため

コンポーネントの種類

  1. Class Component : クラスによって定義されたコンポーネント
  2. Functional Component : 関数型で定義されたコンポーネント

Functional Component

  • ES6のアロー関数で記述
  • stateを持たない(stateless)
  • propsを引数に受け取る
  • JSXをreturnする
  • シンプル
Article.jsx
import React from 'react';

const Article = (props) => {
    return (
        <div>
            <h2>{props.title}</h2>
        </div>
    );
};

export default Article;

Class Component

  • React.Componentを継承
  • ライフサイクルやstateを持つ
  • propsにはthisが必要
  • renderメソッド内でJSXをreturnする
Article.jsx
import React from 'react';

class Article extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div>
              <h2>{this.props.title}</h2>
            </div>
        );
    }
}

export default Article;

最近の主流はFunctional Component

  • 記述量が少ない
  • コンポーネントにstateを持たせたくない

propsでデータを受け渡す

親コンポーネント

Blog.jsx
import React from 'react';
import Article from "./Article";

const Blog = () => {
    return (
        <React.Fragment>
            <Article title={'Hello, React'}/>
        </React.Fragment>
    );
}

export default Blog;

子コンポーネント

Article.jsx
import React from 'react';

const Article = (props) => {
    return (
        <div>
            <h2>{props.title}</h2>
        </div>
    );
};

export default Article;

受け渡せるデータ型

  • {}内に記述
  • 文字列、数値、真偽値、配列、オブジェクトなどなんでも渡せる
  • 文字列は{}なくてもOK
Blog.jsx
import React from 'react';
import Article from "./Article";

const Blog = () => {
    const authorName = 'Eric Clapton';
    return (
        <React.Fragment>
            <Article
                title={'Hello, React.'}
                order={3}
                isPublished={true}
                author={authorName}
            />
        </React.Fragment>
    );
}

export default Blog;

再利用する

コンポーネントは再利用できることが最大の利点

Blog.jsx
import React from 'react';
import Article from "./Article";

const Blog = () => {
    const authorName = 'Eric Clapton';
    return (
        <React.Fragment>
            <Article title={'出生について'}/>
            <Article title={'Cream時代'}/>
            <Article title={'ソロ活動時代'}/>
        </React.Fragment>
    );
}

export default Blog;
13
9
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
13
9