反应导航 route.params 打字稿

Dai*_*vdM 3 typescript reactjs react-native react-navigation react-navigation-bottom-tab

我正在使用 TypeScript 创建一个由 Expo 管理的 React Native 应用程序,并且在 React Navigation 和 TypeScript 方面遇到了一些问题。

我想为 Tab.Screen 组件上的底部选项卡导航器指定图标。

这段代码可以工作,但会抱怨,因为 route.params 可能是未定义的(第 10 行)。

类型“对象”上不存在属性“图标”

我可以在 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>
  )
}
Run Code Online (Sandbox Code Playgroud)

小智 16

现在官方文档已经很好地解释了。工作顺利。

阅读文档:https ://reactnavigation.org/docs/typescript/#type-checking-the-navigator

快速浏览一下它的样子:

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>
Run Code Online (Sandbox Code Playgroud)

然后键入检查您的组件:

interface Props extends NativeStackScreenProps<RootStackParamList, 'Profile'> {
    // other props ...
}

const ProfileScreen: React.FC<Props> = ({ route, navigation }) => {
   // ...
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*ina 11

正确的方法是使用参数定义一个类型,并在创建导航器时将其作为类型参数发送。像这样的东西:

type TabNavigatorParamList = {
  EventListView: { icon: string }
  CreateEvent: { icon: string }
}

const Tab = createBottomTabNavigator<TabNavigatorParamList>(); //*

Run Code Online (Sandbox Code Playgroud)

*我假设您的 Tab 组件是 BottomTabNavigator,但无论create{whatever}Navigator您使用哪种类型,相同的代码都可以工作。

就像这样,您的Tab.Navigator道具Tab.Screen就会有正确的类型route

文档中有更多信息,以及更高级的情况,例如注释挂钩和嵌套导航器。


小智 10

import { RouteProp } from '@react-navigation/native';

  route: RouteProp<{ params: { icon: ICON_TYPE } }, 'params'>
Run Code Online (Sandbox Code Playgroud)

我最近遇到了同样的问题,我想出了这个,它似乎工作正常。

  • 你是摇滚人!太感谢了!找这个很久了 (2认同)