【问题标题】:How to pass parameters to routes using tab navigator (createMaterialBottomTabNavigator)?如何使用选项卡导航器(createMaterialBottomTabNavigator)将参数传递给路由?
【发布时间】:2020-09-13 14:08:54
【问题描述】:

我正在使用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>
);

我只能找到一个名为initialParams 的属性,我不确定在这种情况下使用它是否正确。所以,我想做的是从前一个屏幕GET参数,然后PASS这个参数到这三个屏幕中的每一个!

更新

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

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>
    );
}

【问题讨论】:

  • 建议为这个reactnavigation.org/docs/upgrading-from-4.x/… 使用类似反应上下文的东西。如果您愿意,也可以使用 Redux。您也可以为每个屏幕设置initialParams,但是如果所有屏幕都需要访问current_city_,这当然不是一个好方法
  • @BasvanderLinden 实际上我只需要将参数传递给两个屏幕。所以我可以只使用initialParams?我该如何使用它?

标签: react-native react-navigation react-navigation-v5 react-navigation-bottom-tab


【解决方案1】:

如果您只需要将数据传递到有限数量的屏幕,您可以像这样设置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>
  );
}

然后您可以像这样检索屏幕组件中的参数:

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

  // Do something with it...
}

如果您要将此值传递给许多不同的组件,那么最好使用诸如反应上下文https://reactnavigation.org/docs/upgrading-from-4.x/#global-props-with-screenprops 之类的东西。

【讨论】:

    猜你喜欢
    • 2019-08-23
    • 2020-07-30
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 2020-07-29
    • 2018-12-08
    • 2020-06-11
    • 2020-07-29
    相关资源
    最近更新 更多