reactjs - JSX 元素类型错误:将类型添加到从 .map 函数返回的对象
问题描述
我正在尝试将item
类型添加到从 .map 函数返回的对象中。但是,我收到 JSX 错误,我尝试添加item: JSX.Element
到 Item 类型,但这似乎无法正常工作。有人可以为我澄清一下吗?下面是错误、类型和代码。
错误:
src/ListPicker.tsx:69:28 - error TS2345: Argument of type '(item: Item) => JSX.Element' is not assignable to parameter of type '(value: string, index: number, array: string[]) => Element'.
Types of parameters 'item' and 'value' are incompatible.
Type 'string' is not assignable to type 'Item'.
{props.items.map((item: Item) => {
~~~~~~~~~~~~~~~~~
类型:
// TypeScript: Types
interface Props {
title: string,
items: Array<string>,
onPress: Function,
onValueChange: Function,
}
interface Item {
label: string,
value: string,
key: number | string,
color: string,
};
ListPicker.tsx:
// Render iOS Picker
const renderIOSPicker = () => {
try {
return (
<Picker
selectedValue={value}
onValueChange={selectValue}>
{props.items.map((item: Item) => {
return (
<Picker.Item
label={item.label}
value={item.value}
key={item.key || item.label}
color={item.color}
/>
);
})}
</Picker>
)
}
catch (error) {
console.log(error);
}
};
解决方案
似乎这里的问题是item
(即在您的 map 函数的参数中)的类型与接口items
中定义的数组类型之间的不一致。Props
您的Props
界面将items
字段定义为字符串数组,而您的渲染代码期望该字段是对象items
数组。Item
如果您能够修改和重构您的代码,那么Props
定义为:
interface Props {
title: string,
items: Array<Item>,
onPress: Function,
onValueChange: Function,
}
那么这应该可以解决错误。
推荐阅读
- vba - 使用 VBA 压缩某些文件的宏
- amazon-web-services - 有没有办法使用无服务器部署多个共享相同 lambdas 的 api 网关
- javascript - Tee 图表滚动条实现
- php - Lumen 5.6 - php artisan db:seed 出现错误“类 DatabaseSeeder 不存在”
- visual-studio-code - 如何实现 TypeScript 中定义的接口?
- sonarqube - 如何回滚到 sonarqube 中的旧分析
- spring-boot - 在微服务中获取连接超时错误
- c# - 应用暂停时在 Unity 中序列化的内容
- javascript - 从主方法调用并包括 http-request 授权的子方法的单元测试
- excel - INDEX 列参考与范围