从任何地方导航到子屏幕

时间:2019-06-01 14:31:09

标签: react-native react-navigation

我遇到了一个问题。我想找到一种从任何地方(从每个堆栈)转到特定子屏幕的单一方法。我需要它来处理有关通知选择的导航。 所以医生说,如果我想进入子屏幕,我必须像这样继续:

const navigateAction = NavigationActions.navigate({
     routeName: 'Profile',
     params: {},
     action: NavigationActions.navigate({ routeName: 'SubProfileRoute' 
   }),
});

this.props.navigation.dispatch(navigateAction)  // (1)

仅当我不在“个人资料”堆栈中时,此选项才对我有用。但是,如果我在个人资料堆栈中,导航就会停留在个人资料堆栈的初始屏幕上。

所以我有2个问题: -我们可以使用方法(1)在同一堆栈中移动吗? -是否有办法知道用户当前在哪个堆栈中?
this.props.navigation.state 没有帮助(因为我想要位于特定屏幕上的侦听器中的信息)

非常感谢

1 个答案:

答案 0 :(得分:0)

除了要回答您的问题外,我将建议您一个简单的选择。它是使用react-native-router-flux。它非常易于使用,并通过非常简单的代码解决了您的上述问题。安装模块后,将以下内容添加到您的App.js文件中:

import { Router, Scene, Actions } from 'react-native-router-flux';
import Home from 'homeLocation';
import AnotherPage from 'anotherPageLocation';

const onBackPress = () => {
    if (Actions.state.index === 0) {
      return false
    }
    Actions.pop()
    return true
};
const Routes = () => (
   <Router navigationBarStyle={{// your style}} backAndroidHandler={onBackPress}
      titleStyle = {{// your style}} navBarButtonColor = {"lightgrey"}>
      <Scene key = "root">
         <Scene key = "Home" component = {Home} title = "homePageTitle" initial = {true}/>
         <Scene key = "AnotherPage" component = {AnotherPage} title = "pageTitle" />
        // ...other scenes
      </Scene>
   </Router>
)
export default Routes;

然后,如果要从任何页面转到主页,只需写Actions.Home(),或者如果要转到“ AnotherPage”,只需写Actions.AnotherPage()。如果要进入当前页面,请从const currentpage = Actions.currentScene();获取该页面。它将返回当前场景的名称。有关更多信息,请参阅此page