我需要能够从我注册的屏幕组件中获取当前导航状态。我希望在routes
对象中找到一个navigation.state
对象但是它不在那里。我已经设法通过以下方式设置我的根组件来实现这一点,但是这看起来很复杂,我不能帮助,但认为必须有一种更清洁的方法来实现这一点。
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}}/>
)
}
}
答案 0 :(得分:0)
<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)})
}
}