【问题标题】:Share params state between stack navigators in react-navigation在 react-navigation 中的堆栈导航器之间共享参数状态
【发布时间】:2019-07-04 13:36:29
【问题描述】:

如何将堆栈导航器中的参数共享给嵌套在选项卡导航器中的多个堆栈导航器?

const UsersStack = createStackNavigator(...)
const PostsStack = createStackNavigator(...)
const AlbumsStack = createStackNavigator(...)
const ToDosStack = createStackNavigator(...)

const MainTabNavigator = createBottomTabNavigator({
  PostsStack,
  AlbumsStack,
  ToDosStack
});

const AppNavigator = createAppContainer(
  createSwitchNavigator({
    User: UsersStack,
    Main: MainTabNavigator
  })
);

从UsersStack 中的UsersScreen,我正在使用..

navigation.navigate("Main", { userId: "1" })

在PostsStack 内到达PostsScreen,没有参数

navigation.navigate("Posts", { userId: "1" })

在PostsStack 内到达PostsScreen,参数可用,但仅在PostsStack 上。将选项卡切换到 AlbumsStack 或 ToDosStack 显示没有可用的参数。

预期的输出是在所有堆栈上都有userId 参数。

【问题讨论】:

    标签: react-native react-navigation


    【解决方案1】:

    最好的方法是使用Context API。创建上下文并保存您的用户 ID,然后将 Stack Navigation 组件包装在 Context.Provider

    import NavigationContext from './components/MyContext'
    
    export default class App extends React.Component {
      render() {
        return (
          <NavigationContext.Provider value={{
            "userId": "1"
          }}>
            <AppNavigator />
          </NavigationContext.Provider>
        );
      }
    }
    

    现在使用userId 使用Context.Consumer,它将接收当前上下文值并将其返回到所有堆栈导航器屏幕

    import React from 'react'
    import { View, Text, Button, StyleSheet } from 'react-native';
    import NavigationContext from './MyContext'
    export default class UserScreen extends React.Component {
      constructor(props) {
        super(props)
      }
      _navigate = () => {
        this.props.navigation.navigate('Page2')
      }
      render() {
        return (
          <NavigationContext.Consumer>
            {
              ({ userId }) => {
                return (
                  <View style={styles.container}>
                    <Text>Page  1</Text>
                    <Text>{`UserId ${userId}`}</Text>
                    <Button onPress={this._navigate} title="Navigate to page 2" />
                  </View>)
              }
            }
          </NavigationContext.Consumer>
        )
      }
    }
    

    从这里查看示例https://snack.expo.io/@selvaganesh93/navigationglobalcontextdemo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-24
      • 2020-03-30
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      相关资源
      最近更新 更多