React Navigation - 自定义 goBack 转到不同的导航器

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

我的代码设置就像这样,使用 React Native 和 React Navigation v6:

Tab Navigator
 - Stack A
   - Screen 1
 - Stack B
   - Screen 1
 - Stack C
    - Screen 1
    - Screen 2
    - Screen 3

当我从屏幕 A1 -> C1 -> C2 导航到并使用

navigation.goBack()
时,我最终从 C2 返回到屏幕 A1。我希望能回到 C1。

我不确定我在这里做错了什么。代码:

TabNavigator.js

import 'ScreenA' from './Screens/ScreenA'
import 'ScreenB' from './Screens/ScreenB'
import { StackC } from './Stack'

const TabNavigator = () => {
  return (
    <Tab.Navigator initialRouteName="Home"
                   screenOptions={{
                     header: (props) => <Header {...props} />
                   }}
    >
      <Tab.Screen name="Stack A" component={ScreenA} initialParams={{ type: 'Stack A' }} />
      <Tab.Screen name="Stack B" component={ScreenB} initialParams={{ type: 'Stack B' }} />
      <Tab.Screen name="Stack C" component={StackC} options={{ tabBarButton: () => null }} />
    </Tab.Navigator>
  )
}

Stack.js

import 'ScreenC1' from './Screens/ScreenC1'
import 'ScreenC2' from './Screens/ScreenC2'
import 'ScreenC3' from './Screens/ScreenC3'

const Stack = createNativeStackNavigator()

export const StackC = () => {
  return (
    <Stack.Navigator screenOptions={{headerShown: false, animation: 'none'}}
                     initialRouteName="C1"
    >
      <Stack.Screen name="C1" component={ScreenC1}  />
      <Stack.Screen name="C2" component={ScreenC2} />
      <Stack.Screen name="C3" component={ScreenC3} />
    </Stack.Navigator>
  )
}

编辑:值得注意的是,我在标题中有一个自定义后退按钮,当我在那里查看路由堆栈时,无论我导航到哪里,它总是打印相同的输出...但如果我在 C2 屏幕内打印路由堆栈在那。所以看来我的自定义后退按钮和实际屏幕之间存在脱节。

标题.js

const Header = () => {
  const routes = navigation.getState()?.routes
  console.log('routes', routes.map(route => route.name) // ALWAYS prints [ A1, B1, Stack C]
  return (
    <View>
      {navigation.canGoBack() && <Text onPress={() => navigation.goBack()}>{"< Back"}</Text >}
    </View>
  )
}

导航页面不会更改标题中的输出,但屏幕 C1 中会打印相同的 console.log() :

// [ C1, C2 ]

所以它在屏幕 C2 中是正确的,但在标题中不正确..这是为什么?

react-native react-navigation
1个回答
0
投票

问题出在你对

props.navigation.goBack()
里面的
StackC2
的引用。该引用从选项卡导航器传递到
StackC2
。从 Tab 的角度来看,您在 Tab 中访问的最后一个屏幕是 A1,因此源自 Tab 的
navigation
引用会将您带回 A1。

我没有找到完美的解决方案。我发现的解决方法是获取所有这些导航器上方的导航容器的引用:

<NavigationContainer ref={RootNavigation.navigationRef} />

然后在

const navigation = RootNavigation.navigationRef.current
内使用
StackC2

这样,当我从屏幕 A1 -> C1 -> C2 导航到并使用 navigation.goBack() 时,我将正确反转路径,得到 C2 -> C1 -> A1。

我很抱歉,因为使用全局引用并不是最好的编码模式,但我没有找到满足我需要的更强大的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.