4
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学習ログ No.2

Posted at

コンポーネントの分割

✅ ポイント

1.コンポーネントは小さく分けて管理
→ ファイルごとに分割すると見やすいし再利用しやすい

2.export / importでつなぐ
→ export default Child; → 他のファイルで import Child from "..." して呼べる

Example (親コンポーネント)
 └── Child (子コンポーネント)
       └── List (孫コンポーネント)
Child.tsx
import "./Child.css";         // このコンポーネント専用のCSSを読み込み
import { List } from "./List.jsx";  // 別コンポーネントを読み込み

const Child = () => {
  return (
    <div className="component">
      <h3>Hello</h3>
      <List /> {/* ← ここでListコンポーネントを使ってる */}
    </div>
  );
};

export default Child;  // 他のファイルで使えるように公開
Example.tsx
import Child from "./components/Child"; // Childを読み込み

const Example = () => {
  return <Child />;  // 呼び出して表示
};

フラグメントとルート要素

JSXで返すものは必ず1つのルート要素(=いちばん外側の親要素)である必要がある

NG例:ルート要素が2つある

const NGComponent = () => {
  return (
    <h1>Hello</h1>  // これがルート要素その1
    <p>World</p>    // これがルート要素その2 → エラー!
  );
};

ReactコンポーネントはただのJavaScriptの関数のため、
return できるのは「1つの値」だけ。


OK例1:divやsectionでまとめる

const OKComponent1 = () => {
  return (
    <div>
      <h1>Hello</h1>
      <p>World</p>
    </div>
  );
};

<div> がルート要素になって、h1p を1つにまとめている


OK例2:Fragment(<>...</>)でまとめる

const OKComponent2 = () => {
  return (
    <>
      <h1>Hello</h1>
      <p>World</p>
    </>
  );
};

<>...</>Fragment
実際のHTMLに余計なタグを追加しないで、1つのルート要素として使える

参考にした記事

【React】コンポーネントのimportとexportについて【JavaScript】

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