コンポーネントとJSX

  1. Viteアイコンをコンポーネントにする

    const ViteIcon = () => {
      return (
        <a href="<https://vitejs.dev>" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
      );
    };
    
  2. Viteアイコンコンポーネントを別ファイルにする

  3. Viteアイコンに <div>アイコン**を**クリックするとViteのサイトを開きます</div> というタグを追加する

  4. components ディレクトリを作成し、ViteIcon.tsxReactIcon.tsx をその中に移す

コンポーネント

JSX

コンポーネントのレンダリングとDOMレンダリング


コンポーネントの属性

  1. 「こんにちは」と出力する Greeting コンポーネントを作る

    export const Greeting = () => {
      return <h1>こんにちは</h1>
    }
    
  2. <Greeting name="React" /> で名前を受け取り、「こんにちは React」と出力するように変更する

    type Props = {
      name: string;
    };
    
    export const Greeting = (props: Props) => {
      return <h1>こんにちは {props.name}</h1>
    }
    
  3. <Greeting /> コンポーネントのタグを開き、子要素を追加する

    import { PropsWithChildren } from 'react';
    
    type Props = {
      name: string;
    };
    
    export const Greeting = (props: PropsWithChildren<Props>) => {
      return (
        <>
          <h1>こんにちは {props.name}</h1>
          {props.children}
        </>
      );
    };
    

Props

Children

  1. 名前の配列を元に複数のコンポーネントを作成する

    export const Greeting = ({ names, children }: PropsWithChildren<Props>) => {
      return (
        <>
          {names.map((name) => (
            <h1 key={name}>こんにちは {name}</h1>
          ))}
          {children}
        </>
      );
    };
    

Key