React 18 TypeScript 子 FC 質問する

React 18 TypeScript 子 FC 質問する

React 18 にアップグレードしたら、問題なくコンパイルできました。しかし、現在は、子を使用するすべてのコンポーネントでエラーが発生しているようです。Property 'children' does not exist on type 'IPageProps'.

以前は、children プロパティは自動的にFCインターフェースに含まれていました。現在は手動で追加する必要があるようですchildren: ReactNodeReact の子要素の正しい TypeScript タイプは何ですか?

これは React 18 アップデートの一部ですか、それとも私の環境で何か問題が発生しているのでしょうか?

パッケージ.json

"react": "^18.0.0",
"react-dom": "^18.0.0",
"next": "12.1.4",
"@types/react": "18.0.0",
"@types/react-dom": "18.0.0",

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "alwaysStrict": true,
    "sourceMap": true,
    "incremental": true
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

ベストアンサー1

それでもこの答え正しいですが、絶対にしなければならないこのPropsWithChildrenヘルパーを使用してください。(主にコードモッド(手動での使用ではありません。)

代わりに、手動で定義する方が簡単だと思います。

前に

import * as React from 'react';

type Props = {};
const Component: React.FC<Props> = ({children}) => {...}

import * as React from 'react';

type Props = {
  children?: React.ReactNode
};
const Component: React.FC<Props> = ({children}) => {...}

必要なのはそれだけです。

あるいは、使用をReact.FC完全に中止することもできます。

import * as React from 'react';

type Props = {
  children?: React.ReactNode
};

function Component({children}: Props): React.ReactNode {
  ...
}

React では、childrenは通常のプロパティであり、特別なものではありません。したがって、他のすべてのプロパティを定義するのと同じように定義する必要があります。これを非表示にしていた以前の型指定は間違っていました。

おすすめ記事