繁体   English   中英

如何在 TypeScript react-native 中使用固有属性作为类型

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM