React 18 にアップグレードしたら、問題なくコンパイルできました。しかし、現在は、子を使用するすべてのコンポーネントでエラーが発生しているようです。Property 'children' does not exist on type 'IPageProps'.
以前は、children プロパティは自動的にFC
インターフェースに含まれていました。現在は手動で追加する必要があるようですchildren: ReactNode
。React の子要素の正しい 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
は通常のプロパティであり、特別なものではありません。したがって、他のすべてのプロパティを定義するのと同じように定義する必要があります。これを非表示にしていた以前の型指定は間違っていました。