【React】学習ロードマップ take2 ~props~

React

概要

Reactを学習するにおいて、実際に手を動かすのが吉ということで、アプリケーションを作成します。

元記事

前の記事

次の記事

作成物

基本中の基本Hello Worldを出力するアプリケーションを作成します。

構成は、以下のみです。

- index.html
- index.js
- App.jsx
- Compornents
    - ColorMessage.jsx

実装

今回は、ただHello Worldを返すだけのアプリケーションに色をcssをつけて実装します。

また、compornentsとして、コードを分離して記述しています。

わざわざプロジェクトを作るのは大変だと思うので、code sandbox等で動かしてみてください。

index.js
------------------------
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

index.html
------------------------
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>React App</title>
  </head>

  <body>
    <div id="root"></div>
  </body>
</html>

App.jsx
------------------------
import { ColorMessageChildren } from "./compornents/ColorMessage";
import { ColorMessage } from "./compornents/ColorMessage";

export const App = () => {
  const onClickButton = () => alert();
  return (
    <>
      <h1 style={{ color: "red" }}>こんにちは!</h1>
      {/* タグを省略してこのような書き方ができます */}
      <ColorMessage color="blue" message="Hello World" />
      <ColorMessage color="green" message="Good Night" />
      {/* タグを明記して、従来の書き方もできます */}
      <ColorMessageChildren color="gray">Sorry</ColorMessageChildren>
      <button onClick={onClickButton}>ボタン</button>
    </>
  );
};

ColorMessage.jsx
------------------------
export const ColorMessage = (props) => {
  const { color, message } = props;
  const contentStyle = {
    color: color,
    fontSize: "25px",
  };
  return (
    <>
      <p style={contentStyle}>{message}</p>
    </>
  );
};

export const ColorMessageChildren = (props) => {
  const { color, children } = props;
  const contentStyle = {
    color: color,
    fontSize: "10px",
  };
  return (
    <>
      <p style={contentStyle}>{children}</p>
    </>
  );
};

実際に出力される画面はこちら

学びポイント

props

ここでは、<ColorMessage color=”blue” message=”Hello World” />という形で、引数を持たせています。このような形でケースごとに異なる値を利用できるような仕組みをpropsといいます。

export const ColorMessage = (props) => {
  const { color, message } = props;  ここで、各変数を定義しています。
  const contentStyle = {
    color: color,
    fontSize: "25px",
  };
  return (
    <>
      <p style={contentStyle}>{message}</p>
    </>
  );
};

このように変数を定義しない場合は、props.colorやprops.messageのように記述しましょう。

children

従来のタグのように<p>hogehoge</p>という記述もできます。

ColorMessage.jsxに、<ColorMessageChildren color=”gray”>Sorry</ColorMessageChildren>というように記述しています。

Sorryにあたる箇所がchildrenと呼ばれ、下記のように新たに定義する必要があります。

export const ColorMessageChildren = (props) => {
  const { color, children } = props;
  const contentStyle = {
    color: color,
    fontSize: "10px",
  };
  return (
    <>
      <p style={contentStyle}>{children}</p>
    </>
  );
};

まとめ

実際に手を動かして実装することで、イメージを少し掴めてきました。

また別のアプリケーションも実装していきたいと思います。

コメント

タイトルとURLをコピーしました