我怎样才能做到这一点:
if navigation stack is not empty
this.props.navigation.goBack()
else
this.props.navigation.navigate('CustomScreen')
解决方案解决方案是从前一个屏幕发送参数,并在当前屏幕中检查该参数是否存在
屏蔽1:
this.props.navigation.navigate('Screen2', {prevScreen: 'Screen1'});
屏蔽2:
if(this.props.navigation.getParam('prevScreen', null))
this.props.navigation.goBack();
else
this.props.navigation.navigate('CustomScreen');
this.props.navigation
中有一个叫做dangerouslyGetParent
的函数。你可以在文档here中看到它。
它在文档中声明了以下内容:
另一个很好的用例是在父路由列表中找到活动路由的索引。因此,如果您在索引0处于堆栈的情况下,那么您可能不想渲染后退按钮,但如果您在列表中的其他位置,那么您将渲染后退按钮。
所以我们可以使用以下来获取路由的索引
this.props.navigation.dangerouslyGetParent().state.index
因此,无需传递参数,您可以检查堆栈中的位置,然后决定要执行的操作。
// get the index of the route
let index = this.props.navigation.dangerouslyGetParent().state.index;
// handle the index we get
if (index > 0) {
this.props.navigation.goBack();
} else {
this.props.navigation.navigate('CustomScreen')
}