我正在使用来自https://reactnavigation.org/docs/navigators/tab的React Navigation的标签导航器,当我在标签屏幕之间切换时,我没有在this.props.navigation中获得任何导航状态。
标签导航:
import React, { Component } from 'react';
import { View, Text, Image} from 'react-native';
import DashboardTabScreen from 'FinanceBakerZ/src/components/dashboard/DashboardTabScreen';
import { TabNavigator } from 'react-navigation';
render() {
console.log(this.props.navigation);
return (
<View>
<DashboardTabNavigator />
</View>
);
}
const DashboardTabNavigator = TabNavigator({
TODAY: {
screen: DashboardTabScreen
},
THISWEEK: {
screen: DashboardTabScreen
}
});
DASHBOARD SCREEN:
import React, { Component } from 'react';
import { View, Text} from 'react-native';
export default class DashboardTabScreen extends Component {
constructor(props) {
super(props);
this.state = {};
console.log('props', props);
}
render() {
console.log('props', this.props);
return (
<View style={{flex: 1}}>
<Text>Checking!</Text>
</View>
);
}
}
我首先渲染组件时在Dashboard Screen上获得道具但是当我切换标签时我没有获得道具。 我需要获取当前的屏幕名称,即TODAY或THISWEEK。
答案 0 :(得分:10)
你的问题是关于&#34;屏幕跟踪&#34;,react-navigation
有一个官方指南。您可以使用onNavigationStateChange
使用内置导航容器来跟踪屏幕,或者如果要与Redux集成,则可以编写Redux中间件来跟踪屏幕。更多细节可以在官方指南中找到:Screen-Tracking。以下是使用onNavigationStateChange
:
import { GoogleAnalyticsTracker } from 'react-native-google-analytics-bridge';
const tracker = new GoogleAnalyticsTracker(GA_TRACKING_ID);
// gets the current screen from navigation state
function getCurrentRouteName(navigationState) {
if (!navigationState) {
return null;
}
const route = navigationState.routes[navigationState.index];
// dive into nested navigators
if (route.routes) {
return getCurrentRouteName(route);
}
return route.routeName;
}
const AppNavigator = StackNavigator(AppRouteConfigs);
export default () => (
<AppNavigator
onNavigationStateChange={(prevState, currentState) => {
const currentScreen = getCurrentRouteName(currentState);
const prevScreen = getCurrentRouteName(prevState);
if (prevScreen !== currentScreen) {
// the line below uses the Google Analytics tracker
// change the tracker here to use other Mobile analytics SDK.
tracker.trackScreenView(currentScreen);
}
}}
/>
);
答案 1 :(得分:6)
首先检查所有属性,例如
<Text>{JSON.stringify(this.props, null, 2)}</Text>
上面的json数组将在routeName索引下显示您当前的导航状态,即
this.props.navigation.state.routeName
答案 2 :(得分:1)
您是否尝试在路线对象中定义navigationOptions?
const DashboardTabNavigator = TabNavigator({
TODAY: {
screen: DashboardTabScreen
navigationOptions: {
title: 'TODAY',
},
},
})
您还可以将navigationOptions设置为将使用导航对象调用的回调。
const DashboardTabNavigator = TabNavigator({
TODAY: {
screen: DashboardTabScreen
navigationOptions: ({ navigation }) => ({
title: 'TODAY',
navigationState: navigation.state,
})
},
})
详细了解navigationOptions https://reactnavigation.org/docs/navigators/