React Native 安卓、苹果、鸿蒙5.0 三端适配方案:条件编译 + 平台适配层
下面我提供一个完整的 条件编译+平台适配层
实现方案,让同一套 React Native 代码能同时支持 Android、iOS 和鸿蒙 5.0 设备。
整体架构设计
项目结构
my-app/
├── src/
│ ├── common/ # 完全平台无关的代码
│ ├── components/ # 普通React组件
│ ├── modules/ # 业务模块
│ ├── platforms/ # 平台适配层
│ │ ├── android/ # Android专用实现
│ │ ├── ios/ # iOS专用实现
│ │ └── harmony/ # 鸿蒙专用实现
│ ├── services/ # 核心服务
│ └── App.tsx # 应用入口
├── android/ # RN Android工程
├── ios/ # RN iOS工程
├── harmony/ # 鸿蒙工程
├── babel.config.js # Babel配置
└── package.json
核心实现代码
1. 平台检测工具 (src/utils/platform.ts)
// 平台类型定义
export type PlatformType = 'android' | 'ios' | 'harmony';// 检测当前运行平台
export const getPlatform = (): PlatformType => {// React Native 环境if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {return Platform