LoginSignup
2
1

More than 3 years have passed since last update.

【REACT】Propsをもっと理解しましょう。

Last updated at Posted at 2019-12-29

概要

以前、投稿したPropsとStateの説明の追記です。
まず、part.1のコードを説明しようかと思いましたが、
コード簡単すぎで省略します。
代わりに、part.1で説明しなかったPropsを説明します。

Props

defaultProps

class Main extends Component {
  render() {
    return (
      <div>
        hello! I'am <b>{this.props.name}</b> .
      </div>
    );
  }
}

export default Main;
import Main from './Main';

class Sub extends Component {
  render() {
    return (
      <Main name="Tanaka" />
    );
  }
}

export default Sub;

以前、使ったコードですが、
実は、このコード問題があります。
今は、nameに【Tanaka】で代入していますが、
Propsにvalueを入れるのを忘れたり、
何らかの理由で、Propsを空にする場合があります。

defaultPropsは、Propsのプロパティにデフォルト値を指定することです。
defaultPropsを使って、名前のデフォルト値を'Tom'にします。

class Main extends Component {
  render() {
    return (
      <div>
        hello! I'am <b>{this.props.name}</b> .
      </div>
    );
  }
}

Main.defaultProps = {
  name: 'Tom'
};

export default Main;

他には、

class Main extends Component {
  static defaultProps = {
    name: 'Tom'
  }
  render() {
    return (
      <div>
        hello! I'am <b>{this.props.name}</b> .
      </div>
    );
  }
}

export default Main;

こんな風に使うのができます。

Functional Component

もし、Propsだけ貰って、見せるだけの機能だったら、
componentを使うより、Functional Componentをもっと使います。
上にあるMain Classを修正してみます。

import React from 'react';

const Main = ({ name }) => {
  return (
    <div>
      hello! I'am <b>{name}</b> .
    </div>
  );
};

export default Main;
2
1
1

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
2
1