我正在嘗試使用 typescript 運行 Flatlist,但它似乎只允許一個運算式函式,它的 props 被解構。我似乎無法弄清楚必要型別的結構(建議)。有誰知道如何解決這一問題?
不變的平面串列功能
const renderSuggestions = () =>
<FlatList
data={data}
renderItem={renderItem}
onPress={(item:Suggestion) => handleSelect(item)}
keyExtractor={item => item.place_id}
/>
嘗試 1(錯誤:未找到渲染項多載)
const renderItem = (item:Suggestion)=> (
<View>
<TouchableOpacity >
<Text >{item.structured_formatting.main_text}</Text>
</TouchableOpacity>
</View>
)
嘗試 2(打字稿型別錯誤(隱式任何型別))
const renderItem = ({item})=> (
<View>
<TouchableOpacity >
<Text >{item.structured_formatting.main_text}</Text>
</TouchableOpacity>
</View>
)
每個答案嘗試:未找到專案/索引錯誤
const renderItem = (item:Suggestion, index:number)=> (
<View>
<TouchableOpacity >
<Text >{item.structured_formatting.main_text}</Text>
</TouchableOpacity>
</View>
)
const renderSuggestions = () =>
<FlatList
data={data}
renderItem={({ item:Suggestion, index:number }) => renderItem(item, index)}
onPress={(item:Suggestion) => handleSelect(item)}
keyExtractor={item => item.place_id}
/>
uj5u.com熱心網友回復:
對于 aFlatList傳遞的dataprop 的型別決定了 destructured 的型別item。這是查看此內容的最小作業示例。
import React, { useState } from "react"
import { FlatList } from "react-native"
type DataType = {
id: number,
someThing: string
}
const FlatListWithType = () => {
// we specify the type here
const [data, setData] = useState<DataType[]>()
return (
<FlatList
data={data}
renderItem={({ item, index }) => (
)}
/>
)
}
型別建議現在應該可以作業了。

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/450510.html
上一篇:React-為每個組件迭代計數器
下一篇:導航給了我空白頁
