Component / Props の基本的な使い方
名前なしExport(推奨)
/*** components/Button.jsx (子コンポーネント) ***/
import React from 'react';
const Button = (props) => {
return <button>Hey, {props.name}</button>; // 親が子に渡すデータがpropsに入っています
};
export default Button;
/**** App.jsx (親コンポーネント) ***/
import Button from './components/Button'; // Exportされた子コンポートを親がImportする
function App() {
return (
<>
<Button
name={'Michael'}
/>
</>
)
}
export default App;
※1コンポーネント=1ファイル(コードの見通しを良くするため/別ファイルに分けることでコードが読みやすくなります)
名前付きExport / 名前付きImport
/*** components/index.jsx ***/ <---慣例的にindex.jsxという名前にすること
export {default as Title} from './Title';
export {default as Button} from './Button'; // Button.jsx
export {default as Content} from './Content';
/*** 親コンポーネントファイル ***/
import {Content, Button} from './index';
const Article = (props) => {
return (
<>
<Title title={props.title} />
<Content content={props.content} />
</>
);
};
export default Article;
index.jsxにはcomponentsディレクトリに入った子コンポーネントをまとめます
親コンポーネントはindex.jsx(エントリポイント)から複数の子コンポーネントをImportできます
BACK