我对类型有一个问题。升级到React 18后,我得到组件ItemsList
的以下错误:
<ItemsList items={items} dataTestId='items_list_block'>
{(item) => ( // error
<ItemView
item={item}
/>
)}
</ItemsList> </ItemsList>
ItemsList:
type tItemsListProps<T extends tOptionListItem> = {
children: (item: T) => React.ReactNode;
items: T[];
dataTestId?: string;
};
function ItemsList<T extends tOptionListItem>({
children,
items,
dataTestId,
}: React.PropsWithChildren<tItemsListProps<T>>) {
return (
<Box>
<List>
{items?.map((item) => (
<List.Item key={item.id} data-testid='list_item'>
{children(item)}
</List.Item>
))}
</List>
</Box>
);
}
错误:
TS2322: Type '(item: T) =>元素'不能赋值给类型'(((item: T) =>ReactNode),string) | (((item: T) =>ReactNode),number) | (((item: T) =>ReactNode),false) | (((item: T) =>ReactNode),true) | (((item: T) =>ReactNode),ReactElement<…>) | (((item: T) =>ReactNode),ReactFragment) | (((item: T) =>ReactNode),ReactPortal)"。Type '(item: T) =>元素'不能赋值给类型'((item: T) =>ReactNode),字符串"。Type '(item: T) =>元素'不能赋值给'string'类型。ItemsList。tsx(7,3):期望的类型来自属性'children',它在类型'IntrinsicAttributes &tItemsListProps,{孩子吗?: ReactNode;} '
我知道道具children: (item: T) => React.ReactNode
返回错误的类型,但在React 17中它工作,一切都是正确的。
我改变了返回函数的类型并解决了这个问题
function ItemsList<T extends tOptionListItem>({
children,
items,
dataTestId,
}: tItemsListProps<T>) {
return (
<Box>
<List>
{items?.map((item) => (
<List.Item key={item.id} data-testid='list_item'>
{children(item)}
</List.Item>
))}
</List>
</Box>
);
}