fl427's Studio.

TS报错,Property 'children' does not exist on type 'Props'

字数统计: 168阅读时长: 1 min
2022/09/29

问题

在把项目升级到 React18 后,发现原来没问题的组件,如果使用了 children 属性,TS 就会编译失败,错误信息如下

1
Property 'children' does not exist on type 'Props'.

原因

children属性已经在函数组件中被移除,如果需要使用children属性,则需要手动声明。

解决

第一种方法,手动声明 children 属性。

1
2
3
4
5
import * as React from 'react';
type Props = {
children?: React.ReactNode
};
const Component: React.FC<Props> = ({children}) => {...}

第二种方法,使用PropsWithChildren辅助属性。

1
2
3
import React, { PropsWithChildren } from 'react';
type Props = {};
const Component: React.FC<PropsWithChildren<Props>> = ({children}) => {...}
CATALOG
  1. 1. 问题
  2. 2. 原因
  3. 3. 解决