简体   繁体   English

反应导航获取屏幕中的当前导航状态

[英]React-navigation get current navigation state in screens

I need to be able to get the current navigation state from my registered screen components. 我需要能够从注册的屏幕组件中获取当前的导航状态。 I expected to find a routes object inside the navigation.state object but alas its not there. 我希望在navigation.state对象内找到一个routes对象,但可惜它不在那儿。 I have managed to get this working by setting up my root component in the following way, however this seems convoluted and i cant help but think there must be a cleaner way to achieve this. 我设法通过以下方式设置我的根组件来使此工作正常进行,但是这似乎令人费解,我不禁要想到必须有一种更清洁的方法来实现这一目标。

App.js App.js

import React, {Component} from 'react'
import {Tabs} from './components/Routes'
import {NavigationActions} from 'react-navigation'


export default class App extends React.Component {

    state = {
        navState: null
    }

    componentDidMount(){
        const initState = Tabs.router.getStateForAction(NavigationActions.init())
        this.getState(null, initState);
    }

    getState = (prevState, newState) => {
        let activeIndex = newState.index
        let navState = newState.routes[activeIndex]
        this.setState({navState})
    }

  render() {

    return (
        <Tabs
            onNavigationStateChange={this.getState}
            screenProps={{navState: this.state.navState}}/>
    )

  }

}
<NavigationName
    onNavigationStateChange={(prevState, newState) => {
        this._getCurrentRouteName(newState)
    }}
/>

_getCurrentRouteName(navState) {

    if (navState.hasOwnProperty('index')) {
        this._getCurrentRouteName(navState.routes[navState.index])
    } else {
        console.log("Current Route Name:", navState.routeName)
        this.setState({navState: setCurrentRouteName(navState.routeName)})
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法通过 react-navigation 的导航道具黑白屏幕 - unable to pass navigation props b/w screens with react-navigation 如何使用 react-navigation v5 设置初始状态以将屏幕包含为历史记录? - How can I set the initial state using react-navigation v5 to include screens as history? 即使遵循 react-navigation 文档,react-navigation 也无法在屏幕之间导航 - react-navigation can't navigate between screens even after following react-navigation docs 使用 react-navigation AppContainer 保持状态 - Persist state with react-navigation AppContainer 如何在欢迎屏幕和登录屏幕中禁用反应导航抽屉 - How to disable react-navigation drawer in welcome and sign in screens react-navigation:如何在多个屏幕中包装navigationOptions - react-navigation: How to wrap navigationOptions in multiple screens 如何在底部选项卡导航器 react-navigation 中卸载非活动屏幕? - How to unmount inactive screens in bottom tab navigator react-navigation? 反应导航-底部导航 - React-navigation - Bottom Navigation 在反应本地/反应导航应用程序中存储全局状态? - Storing global state in react-native/react-navigation app? react-navigation:如何根据当前选项卡更改tabBar颜色 - react-navigation: How to change tabBar color based on current tab
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM