繁体   English   中英

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

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

我需要能够从注册的屏幕组件中获取当前的导航状态。 我希望在navigation.state对象内找到一个routes对象,但可惜它不在那儿。 我设法通过以下方式设置我的根组件来使此工作正常进行,但是这似乎令人费解,我不禁要想到必须有一种更清洁的方法来实现这一目标。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM