我在我的專案中使用 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
為什么我會收到這個錯誤,我在這里做錯了什么?
uj5u.com熱心網友回復:
不幸的是,因為 a 的簽名React.FC是它回傳單個ReactElement,map所以傳入串列上的(優雅)將不起作用 - 您實際上回傳了一個ReactElements串列。
您需要將整個東西包裝起來,就像在 a 中一樣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>
))}
</>
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/407202.html
標籤:
