首页 > 解决方案 > createBottomTabNavigator 中的 navigationOptions 的 propTypes 应该在哪里定义?

问题描述

我刚刚应用了 airbnb、prettier、react/prettier 和所有的 linting。我仍然无法绕过这个错误[1],因为我不明白应该在哪里为“内部函数”声明 propTypes 作为这个错误。

我没有给出这些参数,也没有定义它们。正如我在文档中看到的那样,它们来自createBottomTabNavigator 。那么,我应该如何对哪些 props 是必需的tabBarIcon,哪些不是这些 props 的解构有发言权?[2]

更新

[1] 错误是 linting 错误。代码执行得很好。

[2] 我们当然可以稍微摆弄一下以使其正常工作并避免错误,但我的目标是了解它是如何工作的以及为什么它会返回错误,作为官方示例的片段。

export const HomeStackNavigator = createStackNavigator(
    ...
);

export const TabNavigator = createBottomTabNavigator(
  {
    Home: {
      screen: HomeStackNavigator,
    },
    Settings: {
      screen: SettingsStackNavigator,
    },
  },
  {
    initialRouteName: 'Home',
    defaultNavigationOptions: ({ navigation }) => ({
      tabBarIcon: ({ focused, horizontal, tintColor }) => {
        // Getting error here ^^^^^^^^^^^^^^^^^^^^^^^^
        // 'focused' is missing in props validationeslint(react/prop-types)
        const { routeName } = navigation.state;
        let IconComponent = Ionicons;
        let iconName;
        if (routeName === 'Home') {
          iconName = 'ios-home';
          IconComponent = HomeIconWithBadge;
        } else if (routeName === 'Settings') {
          iconName = 'ios-cog';
        }
        return (
          <IconComponent //
            name={iconName}
            color={tintColor}
            size={25}
          />
        );
      },
      headerStyle: {
        backgroundColor: '#f4511e',
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
      },
    }),
    tabBarOptions: {
      // activeTintColor: 'tomato',
      keyboardHidesTabBar: true,
    },
  }
);

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      appState: AppState.currentState,
      isStoreLoading: false,
      store: createStore(rootReducer)
    };
  }

  ...

  componentDidMount(){...}

  ...

  render() {
    const { store, isStoreLoading } = this.state;
    if (isStoreLoading) {
      return <Text>Loading...</Text>;
    }
    return (
      <Provider store={store}>
        <AppContainer />
      </Provider>
    );
  }
}

标签: reactjsreact-nativeeslintreact-proptypes

解决方案


如果你真的想为这样的内部函数定义 prop-types,你需要将它移到导航器之外。

const MyTabBarIcon = ({ focused, horizontal, tintColor, navigation }) => {
    // [...]
}

MyTabBarIcon.propTypes = {
    focused: PropTypes.bool.isRequired,
    tintColor: PropTypes.string.isRequired,
    navigation: PropTypes.object.isRequired,
    horizontal: PropTypes.bool,
}

然后您的 TabNavigator 变为:

// [...]
defaultNavigationOptions: ({ navigation }) => ({
  tabBarIcon: props => <MyTabBarIcon {...props} navigation={navigation} />,
  // [...]
});
// [...]

推荐阅读