6
3

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 3 years have passed since last update.

【React】値の受け渡し Propsとchildren

Posted at

はじめに

Reactでは、値の受け渡しにPropsがあります。そして、propsの特別な受け渡し方法としてchildrenがあります。Propsとchildrenについてまとめていきます。

Props

下記のコードでは、Propsを使って、ColoredMessageコンポーネントに色とメッセージを受け渡しをしています。

App.jsx
import { ColoredMessage } from "./components/ColoredMessage";

export const App = () => {

  return (
    <>
      <ColoredMessage color="blue" message="おげんきですか?" />
      <ColoredMessage color="pink" message="元気です!" />
    </>
  );
};
ColoredMessage.jsx
export const ColoredMessage = (props) => {
  const contentStyle = {
    color: props.color,
    fontSize: "10px",
  };

  return <p style={contentStyle}>{props.message}</p>;
};

children

下記のコードでは、<ColoredMessage></ColoredMessage>で囲んだコードをColoredMessageコンポーネントで、props.childrenで受け取ってます。

App.jsx


import { ColoredMessage } from "./components/ColoredMessage";

export const App = () => {
  return (
    <>
      <ColoredMessage color="blue">おげんきですか?</ColoredMessage>
      <ColoredMessage color="pink">元気です!</ColoredMessage>
    </>
  );
};

ColoredMessage.jsx
export const ColoredMessage = (props) => {
  const contentStyle = {
    color: props.color,
    fontSize: "20px",
  };

  return <p style={contentStyle}>{props.children}</p>;
};

分割代入を使うと短く書ける

ColoredMessage.jsx
export const ColoredMessage = (props) => {
  const { color, children } = props; //propsの分割代入
  const contentStyle = {
    color, //propsを省略できる。そして、color:colorの省略記法が使える
    fontSize: "10px",
  };

  return <p style={contentStyle}>{children}</p>; //propsを省略できる
};

6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?