我正在构建一个React Native应用程序,我正在使用React Navigation V2处理我的导航。
我从the documentation复制粘贴以下代码:
const MainTabs = createBottomTabNavigator(
{ Home: HomeStack, Settings: SettingsStack },
{
navigationOptions: ({ navigation }: NavigationScreenProps) => ({
tabBarIcon: ({ focused, tintColor }) => {
const { routeName } = navigation.state;
let iconName;
if (routeName === "Home") {
iconName = `ios-information-circle${focused ? "" : "-outline"}`;
} else if (routeName === "Settings") {
iconName = `ios-options${focused ? "" : "-outline"}`;
}
// You can return any component that you like here! We usually use an
// icon component from react-native-vector-icons
return <Ionicons name={iconName} size={25} color={tintColor} />;
}
}),
tabBarOptions: {
activeTintColor: "tomato",
inactiveTintColor: "gray"
}
}
)
由于某种原因,打字稿会引发以下错误:
[ts]
Argument of type '{ navigationOptions: ({ navigation }: any) => { tabBarIcon: ({ focused, tintColor }: { tintColor: string | null; focused: boolean; }) => Icon; }; }' is not assignable to parameter of type 'BottomTabNavigatorConfig'.
Types of property 'navigationOptions' are incompatible.
Type '({ navigation }: any) => { tabBarIcon: ({ focused, tintColor }: { tintColor: string | null; focused: boolean; }) => Icon; }' is not assignable to type 'NavigationBottomTabScreenOptions | ((navigationOptionsContainer: NavigationScreenConfigProps & { navigationOptions: NavigationScreenProp<NavigationRoute<NavigationParams>, NavigationParams>; }) => NavigationBottomTabScreenOptions) | undefined'.
怎么可能?我究竟做错了什么?
根据道具的期望,您可能还需要在表达式中投射您传递的内容。所以类似于:
navigationOptions: ({ navigation as any }: any)
根据我的经验,react-navigation在navigationsOptions属性类型方面存在问题。这里的解决方案是 为库创建一个合适的类型 对你所拥有的类型非常具体。
据我所知,弱点是tabBarIcon
函数参数类型。向要解压缩的参数添加显式类型:
...
tabBarIcon: ({ focused, tintColor }:TabBarIconProps) => {
...
返回类型应自动导出。