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で書いた。
