Open2

TS学習

kurosukekurosuke

PropsWithChildren

具体例で理解する

1.通常の型

import React from 'react';

type MyProps = {
  title: string; // タイトル
  children?: React.ReactNode; // 子要素を受け取るための型
};

const MyComponent: React.FC<MyProps> = ({ title, children }) => {
  return (
    <div>
      <h1>{title}</h1>
      <div>{children}</div>
    </div>
  );
};

export default MyComponent;

使用例:

<MyComponent title="こんにちは">
  <p>これは子要素です</p>
</MyComponent>

2.PropsWithChildrenを使った場合

import React, { PropsWithChildren } from 'react';

type MyProps = PropsWithChildren<{
  title: string; // タイトル
}>;

const MyComponent: React.FC<MyProps> = ({ title, children }) => {
  return (
    <div>
      <h1>{title}</h1>
      <div>{children}</div>
    </div>
  );
};

export default MyComponent;

(children?: React.ReactNode;を書かないだけかも...?)

中身

type PropsWithChildren<P = unknown> = P & { children?: ReactNode | undefined };

動き理解

1. ジェネリック型p

  • 任意の型pに対して、childrenプロパティを追加します。

2. children?: React.ReactNode

  • childrenはオプションプロパティで、React.ReactNode型を持ちます。
  • ReactNodeには文字列、数値、React要素、配列、nullなどが含まれます。
kurosukekurosuke

'ReactElement'

Reactで描画される要素(JSX要素やReactコンポーネント)の具体的なインスタンスを表現する型

中身

    interface ReactElement<
        P = any,
        T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>,
    > {
        type: T;
        props: P;
        key: string | null;
    }