WHAT - React Native 的 Expo Router
文章目录
- 核心定义
- 核心理念
- 核心功能解析(Features)
- 1. Native
- 2. Shareable
- 3. Offline-first
- 4. Optimized
- 5. Iteration
- 6. Universal
- 7. Discoverable
- 总结
- 示例:页面结构如何变成导航?
原文:https://docs.expo.dev/router/introduction/
这段文档介绍了 Expo Router 的功能和特点。这是一种基于文件结构的导航方式,类似于 Web 里的 Next.js 或 Remix 的路由系统,但用于 React Native + Web 多端统一开发。
下面我将逐段解释它的含义,帮你理解核心概念和实际用途。
核心定义
Expo Router is a file-based router for React Native and web applications.
解释:
Expo Router 是一个 基于文件系统的路由解决方案,用于 React Native,同时支持 Web 应用。你创建的页面文件(.tsx
文件)本身就自动成为导航路由。
It allows you to manage navigation between screens in your app, allowing users to move seamlessly between different parts of your app’s UI, using the same components on multiple platforms (Android, iOS, and web).
解释:
它基于同一个代码结构(页面和组件),实现多端(iOS / Android / Web)的一致导航体验。你写一次页面,在不同平台通用。
核心理念
It brings the best file-system routing concepts from the web to a universal application — allowing your routing to work across every platform. When a file is added to the app directory, the file automatically becomes a route in your navigation.
解释:
- 类似 Next.js 的自动路由:你在
app/
目录下新建一个settings.tsx
文件,这个页面就能通过/settings
访问。 - 不再需要手动注册
Stack.Screen
或Tab.Screen
。 - 通过文件结构来定义导航结构,更直观易维护。
核心功能解析(Features)
1. Native
Built on top of our powerful React Navigation suite…
解释:
- Expo Router 是建立在
react-navigation
基础上的。 - 所以你熟悉的栈导航、底部 Tab、Drawer 全部支持。
- 但 Expo Router 抽象了一层,让你不再需要手动管理
<Stack.Screen>
等配置。
2. Shareable
Every screen is automatically deep linkable…
解释:
- 每个页面都自动支持 深度链接(Deep Link)。
- 比如你可以通过一个链接打开某个特定页面:
myapp://settings/profile
- 也可以用于 Web 上的链接分享:
https://yourapp.com/settings
3. Offline-first
Apps are cached and run offline-first…
解释:
- 构建出的 App 是默认离线可运行的。
- 支持 Expo 的更新机制(
expo-updates
),即使用户没有网络也能进入 App,等有网络时自动更新。 - 所有的 URL 路由解析也不依赖后端服务器。
4. Optimized
Routes are automatically optimized…
解释:
- 页面是 懒加载 的:即用户不访问,页面组件就不会加载,提高性能。
- 开发环境下也使用 延迟打包,提高编译速度。
- 这对大型 App 尤其重要。
5. Iteration
Universal Fast Refresh…
解释:
- 所有平台都支持 Fast Refresh(热重载),保持快速开发体验。
- “artifact memoization” 是构建优化的一部分,避免每次构建都全量编译,提升速度。
6. Universal
Android, iOS, and web share a unified navigation structure…
解释:
-
一个统一的路由系统,支持三端共享。
-
如果某些页面需要平台特定逻辑,也可以在每个 route 页面里加平台判断,如:
import { Platform } from 'react-native';
7. Discoverable
Build-time static rendering on web, and universal linking to native…
解释:
- Web 端可以预渲染(Static Site Generation,SSR/SSG),对 SEO 友好。
- 原生 App 支持通用链接(Universal Links / Android App Links),也就是说你可以通过网页链接唤起 App 中的具体页面。
总结
Expo Router = 基于文件结构的路由系统,让你像写 Web 那样开发原生 App(iOS / Android / Web)页面导航。
它的核心优势在于:
- 自动注册路由
- 路由即目录结构
- 深度链接、跨平台统一、懒加载优化
- 原生 + Web 都适配
示例:页面结构如何变成导航?
📁 app/┣ 📄 index.tsx → /┣ 📁 settings/┃ ┣ 📄 index.tsx → /settings┃ ┗ 📄 profile.tsx → /settings/profile┣ 📄 about.tsx → /about
你访问 /settings/profile
,就会自动加载 app/settings/profile.tsx
文件。不需要手动写 Stack.Screen
!