/** * 导航服务层 * 提供全局导航功能,解耦组件与导航状态的直接依赖 */ import { NavigationContainerRef, Route } from '@react-navigation/native'; class NavigationService { private navigationRef: NavigationContainerRef | null = null; private isReady: boolean = false; /** * 设置导航引用 */ setNavigationRef(ref: NavigationContainerRef | null): void { this.navigationRef = ref; this.isReady = ref !== null; } /** * 检查导航是否就绪 */ isNavigationReady(): boolean { return this.isReady && this.navigationRef !== null; } /** * 导航到指定路由 */ navigate(routeName: string, params?: any): void { if (!this.isNavigationReady()) { console.warn('[NavigationService] Navigation not ready'); return; } this.navigationRef!.navigate(routeName as any, params); } /** * 返回上一页 */ goBack(): void { if (!this.isNavigationReady()) { console.warn('[NavigationService] Navigation not ready'); return; } this.navigationRef!.goBack(); } /** * 获取当前路由 */ getCurrentRoute(): Route | null { if (!this.isNavigationReady()) { return null; } return this.navigationRef!.getCurrentRoute(); } /** * 获取当前路由名称 */ getCurrentRouteName(): string | null { const route = this.getCurrentRoute(); return route?.name ?? null; } /** * 重置导航到指定路由 */ reset(routes: { name: string; params?: any }[], index: number = 0): void { if (!this.isNavigationReady()) { console.warn('[NavigationService] Navigation not ready'); return; } this.navigationRef!.reset({ index, routes: routes.map(r => ({ name: r.name, params: r.params })), }); } /** * 替换当前路由 */ replace(routeName: string, params?: any): void { if (!this.isNavigationReady()) { console.warn('[NavigationService] Navigation not ready'); return; } this.navigationRef!.dispatch({ type: 'REPLACE', payload: { name: routeName, params }, }); } /** * 导航到根路由 */ navigateToRoot(): void { this.reset([{ name: 'Main' }]); } /** * 导航到认证页面 */ navigateToAuth(): void { this.reset([{ name: 'Auth' }]); } } export const navigationService = new NavigationService();