首页 > 解决方案 > 如何在 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>

MaterialIconsfrom@expo/vector-icons有一个name类型为的属性GLYPHS

当我使用时,iconName: string我收到以下错误:

预期的类型来自属性“名称”,该属性在“IntrinsicAttributes & IntrinsicClassAttributes”类型上声明

我究竟做错了什么?

标签: javascripttypescriptreact-native

解决方案


name问题是组件的属性MaterialIcons需要 a String literal type,而您正在尝试为其分配string类型。

因为包中没有String literal type@types/react-native-vector-iconsor 中导出,所以@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>;

推荐阅读