javascript - 如何在 TypeScript react-native 中使用 Intrinsic 属性作为类型
问题描述
你如何在 typeScript 中使用 Intrinsic 属性作为类型。
我有一个简单的标签导航,如下所示:
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>
MaterialIcons
from@expo/vector-icons
有一个name
类型为的属性GLYPHS
。
当我使用时,iconName: string
我收到以下错误:
预期的类型来自属性“名称”,该属性在“IntrinsicAttributes & IntrinsicClassAttributes”类型上声明
我究竟做错了什么?
解决方案
name
问题是组件的属性MaterialIcons
需要 a String literal type
,而您正在尝试为其分配string
类型。
因为包中没有String literal type
从@types/react-native-vector-icons
or 中导出,所以@expo/vector-icons
您必须为它定义自己的类型。
一种可能的解决方案是将iconName
属性的类型声明为 type'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>;
推荐阅读
- python - Python和openssl的安装---不用yum
- neo4j - 使用变量匹配并在同一变量的结果之间创建关系
- html - 如何防止谷歌网络爬虫将单个页面作为两个不同的页面读取
- javascript - Discord.js 等待 setTimeout 函数完成,然后允许它再次运行
- python - 无法在pycharm中安装dlib
- javascript - 尝试使用 javascript 使用 localStorage.setItem 保存和加载游戏状态但收到类型错误
- python - Tensorflow TPU 错误:随机缓冲区已满?
- java - (单元测试)如何保持扫描仪运行(Java)
- android-constraintlayout - 如何定义垂直堆叠和水平对齐其引用视图的 Flow 虚拟布局?
- python - 系列描述函数熊猫绘图