打字稿错误:'List<Element>'缺少类型"ReactElement<any,any>"中的以下属性:类型、道具、键



我在项目中使用typescript和react,我创建了一个简单的组件,我想在其中映射列表并创建react元素:

const FlightSchedule: React.FC<{ flightRoute: List<Entity<FlightLeg>> }> = ({flightRoute}) => flightRoute.map(route =>
<DescriptionList key={route.get('flightId')}>
<TermDescriptionGroup description={route.get('flightId')}/>
<TermDescriptionGroup description={route.get('flightDate')} topMargin/>
</DescriptionList>)

但是,我得到了以下打字错误:

Type 'List<Element>' is missing the following properties from type 'ReactElement<any, any>': type, props, key

为什么我会出现这个错误,我做错了什么?

不幸的是,因为React.FC的签名是它返回单个ReactElement,所以传入列表上的(优雅的(map将不起作用-您实际上返回了一个ReactElements的列表。

你需要包装整个东西,就像这里的Fragment一样,然后在里面做映射:

const FlightSchedule: React.FC<{ flightRoute: List<Entity<FlightLeg>> }> = ({ flightRoute }) => (
<>
{flightRoute.map((route) => (
<DescriptionList key={route.get('flightId')}>
<TermDescriptionGroup description={route.get('flightId')} />
<TermDescriptionGroup description={route.get('flightDate')} topMargin />
</DescriptionList>
))}
</>
)

相关内容

最新更新