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

Mar*_*rco 0 typescript reactjs

我在项目中使用打字稿和反应,并且创建了一个简单的组件,我想在其中映射列表并创建反应元素:

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>)
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下打字稿错误:

Type 'List<Element>' is missing the following properties from type 'ReactElement<any, any>': type, props, key
Run Code Online (Sandbox Code Playgroud)

为什么我会收到此错误,我在这里做错了什么?

mil*_*use 5

不幸的是,因为 a 的签名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>
    ))}
  </>
)
Run Code Online (Sandbox Code Playgroud)