如何使用选项卡导航器(createMaterialBottomTabNavigator)将参数传递给路由?

8 react-native react-navigation react-navigation-bottom-tab react-navigation-v5

我正在使用createMaterialBottomTabNavigator并且我想将参数传递给路由:

return (
   <Tab.Navigator initialRouteName="Home">
      <Tab.Screen name="Home" component={home_customers} />
      <Tab.Screen name="Favorites" component={favorite_vendors} />
      <Tab.Screen name="More" component={settings_screen} />
   </Tab.Navigator>
);
Run Code Online (Sandbox Code Playgroud)

我只能找到一个名为initialParams该属性的属性,我不确定在这种情况下使用它是否正确。所以,我想做的是从上一个屏幕获取参数并将该参数传递给这三个屏幕中的每一个!

更新

好的,我找到了如何获取参数,但我仍然不知道如何将这些参数传递到路由屏幕!

export default function home_customers_bar({ route, navigation }) {
    const current_city_ = route.params.current_user_city_; //here I get the parameter from the previous screen
    
    return (
        <Tab.Navigator initialRouteName="Home">
            <Tab.Screen name="Home" component={home_customers} />
            <Tab.Screen name="Favorites" component={favorite_vendors} />
            <Tab.Screen name="More" component={settings_screen} />
        </Tab.Navigator>
    );
}
Run Code Online (Sandbox Code Playgroud)

Bas*_*den 13

如果您只需要将数据传递到有限数量的屏幕,您可以initialParams这样设置:

export default function home_customers_bar({route, navigation}) {
  const current_city_ = route.params.current_user_city_; //here I get the parameter from the previous screen

  return (
    <Tab.Navigator initialRouteName="Home">
      <Tab.Screen
        name="Home"
        component={home_customers}
        initialParams={{currentCity: current_city_}}
      />
      <Tab.Screen
        name="Favorites"
        component={favorite_vendors}
        initialParams={{currentCity: current_city_}}
      />
      <Tab.Screen name="More" component={settings_screen} />
    </Tab.Navigator>
  );
}
Run Code Online (Sandbox Code Playgroud)

然后您可以检索屏幕组件内的参数,如下所示:

function home_customers({ route }) {
  const currentCity = route.params.currentCity;

  // Do something with it...
}
Run Code Online (Sandbox Code Playgroud)

如果您打算将此值传递给许多不同的组件,那么最好使用诸如 React context https://reactnavigation.org/docs/upgrading-from-4.x/#global-props- with-screenprops