反应导航选项卡屏幕图标颜色道具类型

react navigation tab screen icon color props type

我将 eslint 与 vs code 一起用于我的 React Native 项目。

我使用 react navigation v5 创建了一个底部标签导航:

 ...
   <Tab.Screen
        name="Contacts"
        component={ContactStackScreen}
        options={{
          tabBarLabel: 'Contacts',
          tabBarColor: COLORS.DEFAULT,
          tabBarIcon: ({color}) => (
            <MaterialCommunityIcons name="contacts" color={color} size={26} />
          ),
        }}
       ...

我遇到颜色道具的 eslint 错误:

'color' 在道具验证中缺失

我试图修复它:

ButtomTabs.propTypes = {
  color: PropTypes.string,
};

但是我得到了这个错误:

propType "color" 不是必需的,但没有相应的 defaultProps 声明

根据文档,

tabBarIcon is a supported option in bottom tab navigator. So we know we can use it on our screen components in the options prop, but in this case chose to put it in the screenOptions prop of Tab.Navigator in order to centralize the icon configuration for convenience. here is an example of using Icon with Tab.Screen

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';

const Tab = createBottomTabNavigator();

function MyTabs() {
return (
<Tab.Navigator
  initialRouteName="Feed"
  tabBarOptions={{
    activeTintColor: '#e91e63',
  }}
>
  <Tab.Screen
    name="Feed"
    component={Feed}
    options={{
      tabBarLabel: 'Home',
      tabBarIcon: ({ color, size }) => (
        <MaterialCommunityIcons name="home" color={color} size={size} />
      ),
    }}
  />
  <Tab.Screen
    name="Notifications"
    component={Notifications}
    options={{
      tabBarLabel: 'Updates',
      tabBarIcon: ({ color, size }) => (
        <MaterialCommunityIcons name="bell" color={color} size={size} />
      ),
    }}
  />
  <Tab.Screen
    name="Profile"
    component={Profile}
    options={{
      tabBarLabel: 'Profile',
      tabBarIcon: ({ color, size }) => (
        <MaterialCommunityIcons name="account" color={color} size={size} />
      ),
    }}
  />
</Tab.Navigator>

); }

忽略警告。这是误报。

  1. tabBarIcon 不是组件,propTypes 仅适用于组件
  2. 您正在 BottomTabs 组件上添加 propTypes,但警告可能来自 eslint 插件,假设传递给 tabBarIcon 的函数是一个组件

我认为之前的答案对导致 eslint 在这种情况下抛出 react/prop-types 错误的原因存在误解。 lint 错误是正确的——缺少的是为 tabBarIcon 引入的箭头函数的 props 验证。由于箭头函数 returns 是一个 React 组件,eslint 在执行 react/prop-types 规则时是正确的。为了满足该规则,您需要为该箭头函数提供 prop 类型(将箭头函数视为将 color 作为 prop 的匿名组件)。只需添加 {color: string} 作为该箭头函数的整个参数的类型定义,如下所示:

({color}: {color: string}) =>

在上下文中:

<Tab.Screen
        name="Contacts"
        component={ContactStackScreen}
        options={{
          tabBarLabel: 'Contacts',
          tabBarColor: COLORS.DEFAULT,
          tabBarIcon: ({color}: {color: string}) => (
            <MaterialCommunityIcons name="contacts" color={color} size={26} />
          ),
        }}