React 18
ReactのPropsとは
プロパティを設定して関数定義で動的にすること。
プロパティを設定
colorとmessageの2つのプロパティを設定。
import { ColorfulBox } from "./components/ColofulBox";
export const App = () => {
  return (
    <>
      <ColorfulBox color="blue" message="青色です"/>
      <ColorfulBox color="green" message="緑色です"/>
    </>
  );
};プロパティを関数で定義
プロパティを動的に使用できるように関数で定義します。
export const ColorfulBox = (props) => {
    const colorStyle = {
       color : props.color,
    };
  return <p style={colorStyle}>{props.message}</p>;
};childrenを使用
作成したコンポーネント<ColorfulBox>に</ColorfulBox>をつけてコンテントをはさむようにします。
そうするとこのはさまれたコンテントをchildrenとして使用可能になります。
import { ColorfulBox } from "./components/ColorfullBox";
export const App = () => {
  return (
    <>
      <ColorfulBox color="blue">青です</ColorfulBox>
      <ColorfulBox color="green">緑です</ColorfulBox>
    </>
  );
};よって、ColofullBoxコンポーネントはこうなります。
export const ColorfulBox = (props) => {
  const colorStyle = {
    color : props.color
  };
  return <p style={colorStyle}>{props.children}</p>;
};分割代入を使用する場合
分割代入を使って書く場合は、こうなります。
props.color がcolorに
props.childrenがchildrenと書けます。
export const ColorfulBox = (props) => {
 const { color, children } = props;
  const colorStyle = {
    color: color
  };
  return <p style={colorStyle}>{children}</p>;
};この分割代入をいきなり引数に書くこともできます。
下のコードだけを見ると分かりにくいですが、
上のコードが元だと分かれば理解しやすくなります。
export const ColorfulBox = ({ color, children }) => {
  const colorStyle = {
    color
  };
  return <p style={colorStyle}>{children}</p>;
};colorはオブジェクトの省略記法で書いています。
分割代入やオブジェクトの省略記法についてはこちら↓をご覧ください。

 
  
  
  
  