我有这种情况,我有一个嵌套在另一个StackNavigator中的TabNavigator中的StackNavigator. const TabOneStack = StackNavigator({ ScreenA: { screen: ScreenA }, ScreenB: { screen: ScreenB }});const MainTabs = TabNavigator({ TabOne:
const TabOneStack = StackNavigator({ ScreenA: { screen: ScreenA }, ScreenB: { screen: ScreenB } }); const MainTabs = TabNavigator({ TabOne: { screen: TabOneStack }, TabTwo: { screen: TabTwoStack } }); const Root = StackNavigator({ HomeScreen: { screen: HomeScreen }, MainTabs: { screen: MainTabs } });
一切正常但我无法弄清楚如何从ScreenA导航到根StackNavigator中的主屏幕.
在HomeScreen之后,用户直接导航到ScreenA.
ScreenA标题中的后退按钮工作正常并将我带回Home但需要一种方法来使用一个按钮将我带回HomeScreen.
不幸的是,this.props.navigation.goBack()不起作用.
我也试过了
const backAction = NavigationActions.reset({ index: 0, key: null, actions: [ NavigationActions.navigate({ routeName: 'HomeScreen'}) ] }); this.props.navigation.dispatch(backAction));
但我得到:
没有为关键HomeScreen定义路由.必须是以下之一:’ScreenA’,’ScreenB’.
这样做的正确方法是什么?
要从子StackNavigator遍历到父StackNavigator,请执行:class ScreenA extends Component { render() { return (<Button onPress={() => { this.props.navigation.dispatch({type: 'Navigation/BACK'}); }} title='ScreenA. back to Home' />); } }
带有’Navigation / BACK’的this.props.navigation.dispatch()与最顶层的后退按钮完全相同.
它与goBack()的不同之处在于应用父子堆栈遍历,而goBack()则不然.
结果:
请注意@Jigar的回答也是正确的,它只是我的简写符号.关键是将null参数传递给goBack().没有它,它将无法运作.
this.props.navigation.goBack(null);