【发布时间】:2020-04-29 15:34:39
【问题描述】:
我正在尝试将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);
}
};
【问题讨论】:
-
看起来你的道具将
items定义为一个字符串数组,所以当映射一个字符串数组时,映射回调签名是(element: string, index: number, array: string[])。我认为如果您将items的道具接口更新为items: Array<Item>,,它现在应该匹配。如果这是正确的,那么我可以添加为答案。
标签: reactjs typescript react-native types typescript-typings