特定于平台的扩展和模块
编辑页面
学习如何在 Expo Router 中使用特定于平台的扩展以及来自 React Native 的 Platform 模块,根据平台切换模块。
For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.
在构建应用时,你可能希望根据当前平台显示特定内容。平台特定扩展和 Platform 模块可以让在某个平台上的体验更接近原生。以下各节介绍了如何使用 Expo Router 实现这一点。
平台特定扩展
警告 平台特定扩展是在 Expo Router
3.5.x中添加的。如果你使用的是该库的较旧版本,请遵循 平台特定模块 中的说明。
使用平台特定扩展有两种方式:
在 src/app 目录内
Metro bundler 的平台特定扩展(例如 .android.tsx、.ios.tsx、.native.tsx 或 .web.tsx)仅在 src/app 目录中受支持,前提是同时存在一个非平台版本。这可以确保路由在各个平台上都是通用的,以便进行深度链接。
考虑以下项目结构:
srcapp_layout.tsx_layout.web.tsxindex.tsxabout.tsxabout.web.tsx在上述文件结构中:
- _layout.web.tsx 文件在 web 上作为布局使用,而 _layout.tsx 文件在所有其他平台上使用。
- index.tsx 文件在所有平台上用作首页。
- about.web.tsx 文件在 web 上用作关于页面,而 about.tsx 文件在所有其他平台上使用。
在 src/app 目录外
你可以在 src/app 目录之外创建带有平台特定扩展名的文件(例如 .android.tsx、.ios.tsx、.native.tsx 或 .web.tsx),并在 src/app 目录内使用它们。
考虑以下项目结构:
srcapp_layout.tsxindex.tsxabout.tsxcomponentsabout.tsxabout.ios.tsxabout.web.tsx在上述文件结构中,设计要求你为每个平台构建不同的 about 界面。在这种情况下,你可以在 src/components 目录中使用平台扩展为每个平台创建一个组件。导入时,Metro 会确保根据当前平台使用正确的组件版本。然后,你可以将该组件重新导出为 src/app 目录中的一个屏幕。
export { default } from '@/components/about';
平台模块
你可以使用 React Native 的 Platform 模块来检测当前平台,并根据结果渲染相应的内容。例如,你可以在原生平台上渲染 Tabs 布局,而在 web 上渲染自定义布局。
import { Platform } from 'react-native'; import { Link, Slot, Tabs } from 'expo-router'; export default function Layout() { if (Platform.OS === 'web') { // 在 web 上使用一个基础的自定义布局。 return ( <div style={{ flex: 1 }}> <header> <Link href="/">首页</Link> <Link href="/settings">设置</Link> </header> <Slot /> </div> ); } // 在原生平台上使用原生底部标签布局。 return ( <Tabs> <Tabs.Screen name="index" options={{ title: '首页' }} /> <Tabs.Screen name="settings" options={{ title: '设置' }} /> </Tabs> ); }