React Navigation使用中跟踪屏幕切换

定义所使用的导航栈

const RootStack = StackNavigator(
    // ... 略去具体内容
);

工具方法:获取当前屏幕名称

// 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;
}

在使用的导航栈上监听屏幕变化

export default class App extends Component {
//... 其他代码

 render() {
        return (<RootStack  onNavigationStateChange={(prevState, currentState) => {
                const currentScreen = getCurrentRouteName(currentState);
                const prevScreen = getCurrentRouteName(prevState);
                if (prevScreen !== currentScreen) {
                    console.log("当前屏幕切换到了:" + currentScreen);
                }
            }}
        />);
    }

//... 其他代码
}

参考资料

Screen Tracking

猜你喜欢

转载自blog.csdn.net/andy_zhang2007/article/details/80135638