0
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?

[React] コンポーネント

0
Posted at

Reactのコンポーネントの使い方

以下、前回の記事のコード

export const App = () => {
  const onClickButton = () => alert('ボタンを押した!');

  const contentStyle = {
    color: 'blue',
    fontSize: '18px',
  };

  const contentStyle2 = {
    color: 'green',
    fontSize: '22px',
  };

  return (
    <>
      <h1 style={{ color: 'red' }}>こんにちは</h1>
      <p style={contentStyle}>元気ですか</p>
      <p style={contentStyle2}>元気です!</p>
      <button onClick={onClickButton}>ボタン</button>
    </>
  );
};

上記、contentStyle で スタイル指定をしているが、複数個ある場合は、contentStyleを複数個用意しないといけない。
そこで、これをコンポーネント化してみる。

ColorfulMessage.jsx というファイルを新規作成し、(componentsフォルダの中に入れた)
中身は以下のようにする。

ColorfulMessage.jsx
export const ColorfulMessage = (props) => {
  const { color, children } = props;
  const contentStyle = {
    color,
    fontSize: '18px',
  };

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

上記のcontentStyleは、

  const contentStyle = {
    color,
    fontSize: '18px',
  };

以下の color: color を省略して書いたもの。同じ名前なら略せるらしい。

  const contentStyle = {
    color: color,
    fontSize: '18px',
  };

App.jsx は以下のようにする。

App.jsx
import { ColorfulMessage } from './components/ColorfulMessage';

export const App = () => {
  const onClickButton = () => alert('ボタンを押した!');

  return (
    <>
      <h1 style={{ color: 'red' }}>こんにちは</h1>
      <ColorfulMessage color="blue">元気ですか??</ColorfulMessage>
      <ColorfulMessage color="green"> 元気です!</ColorfulMessage>

      <button onClick={onClickButton}>ボタン</button>
    </>
  );
};

下記コードのprops には、
<ColorfulMessage color="blue">元気ですか??</ColorfulMessage>
と指定したら、props.color には、"blue"が入ってくる。
また、props.children には、ColorfulMessageタグで挟まれた "元気ですか??"が入る。

export const ColorfulMessage = (props) => {
  const { color, children } = props;
  const contentStyle = {
    color,
    fontSize: '18px',
  };

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

childrenを使うか、propsを使うかはケースバイケースらしい。

stackblitzで書いた。

スクリーンショット 2026-08-29 230057.png

0
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
0
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?