我在项目中使用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
将不起作用-您实际上返回了一个ReactElement
s的列表。
你需要包装整个东西,就像这里的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>
))}
</>
)