我正在用TypeScript创建一个Expo管理的React Native应用程序,但React Navigation和TypeScript存在一些问题。
我想在选项卡屏幕组件上指定底部选项卡导航器的图标。
此代码有效,但由于route.params可能未定义(第10行(,因此会出现问题。
属性"icon"在类型"object"上不存在
我可以在initialParams上制作所需的图标道具吗?
我查了一下文件,运气不好。
const App: React.FC<{}> = () => {
return (
<SafeAreaView style={styles.container}>
<NavigationContainer>
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ size, color }) => (
<MaterialIcons
size={size}
/* ===> */ name={route.params.icon}
color={color}
/>
),
})}
>
<Tab.Screen
name="EventListView"
initialParams={{ icon: 'view-agenda' }}
component={EventListScreen}
/>
<Tab.Screen
name="CreateEvent"
initialParams={{ icon: 'public' }}
component={SettingsScreen}
/>
</Tab.Navigator>
</NavigationContainer>
</SafeAreaView>
)
}
import { RouteProp } from '@react-navigation/native';
route: RouteProp<{ params: { icon: ICON_TYPE } }, 'params'>
我最近也遇到了同样的问题,我想出了这个,看起来效果很好。
正确的方法是用params定义一个类型,并在创建导航器时将其作为类型参数发送。类似这样的东西:
type TabNavigatorParamList = {
EventListView: { icon: string }
CreateEvent: { icon: string }
}
const Tab = createBottomTabNavigator<TabNavigatorParamList>(); //*
*
我假设您的Tab组件是BottomTabNavigator,但无论您使用哪种类型的create{whatever}Navigator
,都可以使用相同的代码。
就像你的Tab.Navigator
和Tab.Screen
将为他们的route
道具拥有正确的类型一样。
文档中有更多信息,还有更高级的情况,如注释挂钩和嵌套导航器。
它现在在官方文档中得到了很好的解释。工作良好。
阅读文档:https://reactnavigation.org/docs/typescript/#type-检查导航
以下是它的快速外观:
import { createStackNavigator } from '@react-navigation/stack';
type RootStackParamList = {
Home: undefined;
Profile: { userId: string };
Feed: { sort: 'latest' | 'top' } | undefined;
};
const RootStack = createStackNavigator<RootStackParamList>();
<RootStack.Navigator initialRouteName="Home">
<RootStack.Screen name="Home" component={Home} />
<RootStack.Screen
name="Profile"
component={Profile}
initialParams={{ userId: user.id }}
/>
<RootStack.Screen name="Feed" component={Feed} />
</RootStack.Navigator>
然后键入检查您的组件:
interface Props extends NativeStackScreenProps<RootStackParamList, 'Profile'> {
// other props ...
}
const ProfileScreen: React.FC<Props> = ({ route, navigation }) => {
// ...
}