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 1 year has passed since last update.

Propsについて理解する

1
Posted at

Propsの概念について簡単にまとめたものを忘備録としてまとめたものになります。

Propsとは

Propsはコンポーネントに渡すデータ(引数のようなもの)のことを指す。

Propsを用いたデータの渡し方・データの受け方

Propsを用いたデータの渡し方・データの受け方の基本的な書き方は以下の通り。

データの渡し方

<子コンポーネント名 子コンポーネントの値={親コンポーネントが渡すデータ} />

データの受け方(子コンポーネント)

export const 子コンポーネント名 = (props) => {
  console.log(props);
}

子コンポーネント側はデータを受け取る際、関数の引数 (props) で親コンポーネントからデータを受け取っています。

props = { 子コンポーネントの値: { 親コンポーネントの渡すデータ } }

子コンポーネントでその値を使いたい場合、以下のように書くことができる。

<p>{props.子コンポーネントの値}</p>

Propsを分割代入取り出す書き方

子コンポーネントでprops.で書くことが面倒な人は、分割代入でpropsのオブジェクトを取り出す書き方もある。

propsを分割代入して取り出す場合は、以下の書き方になる。

export const 子コンポーネント名 = (props) => {
  // Propsを分割代入
  const { 子コンポーネントの値 } = props;
}

childrenを用いた書き方

コンポーネントでは、以下のように任意の要素を囲って使用することができる。
コンポーネントに囲まれた部分がchildrenとしてPropsに設定される。

親コンポーネント

<TextMessage color="red">テスト</TextMessage>

子コンポーネント

export const TextMessage = (props) => {
  const { color, children } = props;

  const textStyle = {
    color: color,  // colorで省略することもできる
    fontSize: "16px"
  };

  return <p style={textStyle}>{children}</p>
}
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?