问题
在把项目升级到 React18 后,发现原来没问题的组件,如果使用了 children 属性,TS 就会编译失败,错误信息如下
Property 'children' does not exist on type 'Props'.
package.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",
源代码如下
import * as React from 'react';
type Props = {};
const Component: React.FC<Props> = ({children}) => {...}
原因
children
属性已经在函数组件中被移除,如果需要使用 children
属性,则需要手动声明。
解决
第一种方法,手动声明 children 属性。
import * as React from 'react';
type Props = {
children?: React.ReactNode
};
const Component: React.FC<Props> = ({children}) => {...}
第二种方法,使用 PropsWithChildren
辅助属性。
import React, { PropsWithChildren } from 'react';
type Props = {};
const Component: React.FC<PropsWithChildren<Props>> = ({children}) => {...}