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

时间:2020-07-02 11:26:23

标签: react-native eslint react-proptypes eslint-config-airbnb

我将eslint与vs代码一起用于我的本机项目。

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

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

我遇到了彩色道具的错误:

道具验证中缺少“颜色”

我试图修复它:

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

但是我遇到了这个错误:

propType“颜色”不是必需的,但没有相应的defaultProps声明

3 个答案:

答案 0 :(得分:1)

忽略警告。是误报。

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

答案 1 :(得分:0)

根据文档

tabBarIcon是底部标签导航器中受支持的选项。因此,我们知道可以在options道具的屏幕组件上使用它,但在这种情况下,选择将其放在Tab.Navigator的screenOptions道具中,以便集中图标配置,以便于使用。 这是将IconTab.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>

); }

答案 2 :(得分:0)

我相信之前的答案对导致 eslint 在这种情况下抛出 react/prop-types 错误的原因存在误解。 lint 错误是正确的 - 缺少的是为 tabBarIcon 引入的箭头函数的 props 验证。由于该箭头函数返回一个 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} />
          ),
        }}
相关问题