[英]How to use an Intrinsic attributes as types in TypeScript react-native
如何在 typeScript 中使用固有屬性作為類型。
我有一個簡單的標簽導航,如下所示:
const getOptions = (iconName: string) => ({
tabBarIcon: ({ color }: { color: string }) => (
<MaterialIcons name={iconName} size={24} color={color} />
),
});
<Tab.Navigator>
<Tab.Screen
name="HomeScreen"
component={HomeScreen}
options={() => getOptions("home")}
/>
</Tab.Navigator>
@expo/vector-icons
中的MaterialIcons
具有GLYPHS
類型的屬性name
。
當我使用iconName: string
時,我收到以下錯誤:
預期的類型來自屬性“名稱”,該屬性在“IntrinsicAttributes & IntrinsicClassAttributes”類型上聲明
我究竟做錯了什么?
問題是MaterialIcons
組件的屬性name
需要一個String literal type
,而您正在嘗試為其分配一個string
類型。
因為沒有從@types/react-native-vector-icons
或@expo/vector-icons
package 中導出的String literal type
,所以您必須為它定義自己的類型。
一個可能的解決方案是將iconName
屬性的類型聲明為'home'
而不是string
類型:
const getOptions = (iconName: 'home') => ({
tabBarIcon: ({ color }: { color: string }) => (
<MaterialIcons name={iconName} size={24} color={color} />
),
});
<Tab.Navigator>
<Tab.Screen
name="HomeScreen"
component={HomeScreen}
options={() => getOptions("home")}
/>
</Tab.Navigator>
當然,如果您需要更多圖標名稱,則必須擴展此類型。 例如,如果您想在將來向您的Tab.Navigator
添加文章屏幕:
// iconName is of 'home' | 'article' string literal type now
const getOptions = (iconName: 'home' | 'article') => ({
tabBarIcon: ({ color }: { color: string }) => (
<MaterialIcons name={iconName} size={24} color={color} />
),
});
<Tab.Navigator>
<Tab.Screen name="HomeScreen" component={HomeScreen} options={() => getOptions('home')} />
<Tab.Screen
name="ArticleScreen"
component={ArticleScreen}
options={() => getOptions('article')}
/>
</Tab.Navigator>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.