平台特定扩展和模块
编辑
学习如何在 Expo Router 中使用平台特定扩展和 React Native 的 Platform 模块根据平台切换模块。
在构建应用时,您可能希望根据当前平台显示特定内容。平台特定扩展和 Platform 模块可以使体验更符合特定平台的原生感觉。以下部分描述了您如何在 Expo Router 中实现这一点。
平台特定扩展
警告 平台特定扩展在 Expo Router
3.5.x中添加。如果您正在使用较旧版本的库,请遵循平台特定模块的说明。
有两种方法可以使用平台特定扩展:
在应用目录内
Metro 打包器的PLATFORM特定扩展(例如,.android.tsx,.ios.tsx,.native.tsx,或 .web.tsx)仅在存在 非平台版本 时才支持在 app 目录中。这确保了路由在各个平台之间对深度链接是通用的。
考虑以下项目结构:
app_layout.tsx_layout.web.tsxindex.tsxabout.tsxabout.web.tsx在上述文件结构中:
- _layout.web.tsx 文件在网页上作为布局使用,而 _layout.tsx 在所有其他平台使用。
- index.tsx 文件作为所有平台的首页使用。
- about.web.tsx 文件作为网页的关于页面使用,而 about.tsx 文件在所有其他平台使用。
在应用目录外
您可以在 app 目录之外创建平台特定的文件,扩展名可为(例如,.android.tsx,.ios.tsx,.native.tsx,或 .web.tsx),并从 app 目录中使用它们。
考虑以下项目结构:
app_layout.tsxindex.tsxabout.tsxcomponentsabout.tsxabout.ios.tsxabout.web.tsx在上述文件结构中,设计要求您为每个平台构建不同的 about 屏幕。在这种情况下,您可以在 components 目录中为每个平台使用平台扩展创建一个组件。当导入时,Metro 将确保根据当前平台使用正确的组件版本。然后,您可以在 app 目录中将该组件重新导出为屏幕。
app/about.tsx
export { default } from '../components/about';
平台模块
您可以使用来自 React Native 的 Platform 模块来检测当前平台,并根据结果渲染适当的内容。例如,您可以在原生上渲染 Tabs 布局,而在网页上渲染自定义布局。
app/_layout.tsx
import { Platform } from 'react-native'; import { Link, Slot, Tabs } from 'expo-router'; export default function Layout() { if (Platform.OS === '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> ); }