我对React导航的期望正确吗?

时间:2018-12-24 11:10:08

标签: reactjs navigation native expo stack-navigator

可能是我缺乏理解,但是有人会解释我对React导航的期望是否错误吗?

我的应用或多或少是一个问卷,其中一个屏幕可以处理所有问题。基本上,它使用新的问题ID导航到自身。这将获取适当的数据并显示它。工作正常,但是当我按回去时,我不会转到上一个问题,而是转到主页。我使用expo及其recommended navigation

我的期望是当我从最后一页返回时:

Homepage => QuestionPage(id=1) => QuestionPage(id=3) 

我将返回id = 1的QuestionPage,但它会转到Homepage。我在两个页面上都使用了withNavigation来维护导航道具。

这种期望是错误的,还是这种正确的导航行为?如果是这样,那么任何提示该怎么做才能达到我的预期行为。

3 个答案:

答案 0 :(得分:0)

从单个页面实现React Navigation多页面应用程序。您需要在项目中添加“ react-router-dom”包。

import {
  Route as Router,
  Switch,
  Redirect
} from 'react-router-dom';

您必须按照以下步骤为导航页面设置路由器。

<Switch>
<Router exact path="/questionpage/:handle" component={Questionpage} />
</Switch>

在“问题”页面中的路由器:

this.props.match.params.handle // will help to get page number

使用上述语法,您可以获得页码,并可以获取所需的确切数据。

答案 1 :(得分:0)

如果您使用的是StackNavigator,并且从后退按钮上的QuestionPage中进行操作

 this.props.navigation.goBack();

代替

this.props.navigation.navigate('Screen')} 

它应该工作!

如果您想在react导航屏幕上进行自定义导航,请在backAndroid上,建议像这样收听didFocus:

_didFocusSubscription;
  _willBlurSubscription;

  constructor(props) {
    super(props);
    this._didFocusSubscription = props.navigation.addListener('didFocus', payload =>
      BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
    );
  }

  componentDidMount() {
    this._willBlurSubscription = this.props.navigation.addListener('willBlur', payload =>
      BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
    );
  }
hardwareBackPress = () => {  this.props.navigation.navigate('Screen')} }

更准确的示例及其相关文档在https://reactnavigation.org/docs/en/custom-android-back-button-handling.html

答案 2 :(得分:0)

这是如此简单。代替

this.props.navigation.navigate('Question', {id=40})}

我不得不写

this.props.navigation.push('Question', {id=40})}