如何在 React Navigation 中管理嵌套导航器之间的导航?

问题描述 投票:0回答:0

我正在使用 React Navigation v5 开发 React Native 应用程序,但我无法获得我想要的行为。

  • 我有一个包含三个屏幕的 Stack Navigator:“A”、“B”和“C”。
  • C 是一个嵌套的 Stack Navigator,有两个屏幕:“C-1”和“C-2”。

这是我想要的所有行为:

  • 如果用户点击 B 中的按钮,它应该打开 C-1 如果该嵌套导航器中没有以前的导航状态,否则它应该打开最后一个活动/打开的屏幕(例如 C-2)。
  • 如果用户按下 C-2 中的按钮,它应该将他们直接带回屏幕 B(即在父导航器中)。您可以将其视为立即返回 B 的关闭按钮。
  • 从 B 导航到 C-2 后,按标题中的后退按钮应该带我回到 C-1,而不是 B。

我应该如何处理这些要求?我面临着多重挑战 - 例如,当我从 B 导航到 C-2,将 C 和 C-2 作为目标屏幕传递时,标题后退按钮无法按预期工作。它带我回到 B 而不是 C-1。

这是代码...

创建两个堆栈:

const HomeStack = createStackNavigator();
const CStack = createStackNavigator();

创建父堆栈:

class App extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <NavigationContainer>
        <HomeStack.Navigator
          initialRouteName="B"
          screenOptions={{
            cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
          }}>
          <HomeStack.Screen name="A">
            {props => (
              <View>
                <Text>A content</Text>
              </View>
            )}
          </HomeStack.Screen>
          <HomeStack.Screen name="B">
            {props => (
              <View>
                <Button
                  title="Navigate to C"
                  onPress={() => {
                    // props.navigation.navigate('C')
                    // OR
                    // props.navigation.navigate('C', {screen: 'C-2'});
                  }}
                />
              </View>
            )}
          </HomeStack.Screen>
          <HomeStack.Screen name="C">
            {props => <C {...props} />}
          </HomeStack.Screen>
        </HomeStack.Navigator>
      </NavigationContainer>
    );
  }
}

创建嵌套堆栈:

class C extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <CStack.Navigator
        initialRouteName="C-1"
        screenOptions={{
          headerShown: false,
          cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        }}>
        <CStack.Screen name="C-1">
          {props => (
            <View>
              <Text>C-1</Text>
            </View>
          )}
        </CStack.Screen>
        <CStack.Screen name="C-2">
          {props => (
            <View>
              <Text>C-2</Text>
              <Button
                title="Close C navigator"
                onPress={() => props.navigation.navigate('B')}
              />
            </View>
          )}
        </CStack.Screen>
        <CStack.Screen name="C-3">
          {props => (
            <View>
              <Text>C-3</Text>
            </View>
          )}
        </CStack.Screen>
      </CStack.Navigator>
    );
  }
}

感谢您的帮助!

javascript reactjs react-native react-navigation
© www.soinside.com 2019 - 2024. All rights reserved.