@hxa-rn/react-native-i18n
v2.0.15-beta.1
Published
Provide I18n to your React Native application
Readme
本项目基于 react-native-i18n开发。如果在使用过程中有任何问题,欢迎在AtomGit提交Issue,会及时跟进。
项目介绍
@hxa-rn/react-native-i18n 是 react-native-i18n 的鸿蒙(OpenHarmony)适配版本,当前规范版本号为 2.0.15-beta.1。
本库通过 TurboModule RNI18n 读取系统偏好语言,JS 层复用 i18n-js 提供翻译与本地化能力。
| 鸿蒙适配包版本 | 原始库版本 | 支持 RN 版本 | Autolink | | ------------ | ---------- | ------------ | -------- | | 2.0.15-beta.1 | 2.0.15 | 0.72+ | 是 |
集成指南
npm install @hxa-rn/react-native-i18npeerDependencies:react-native(>=0.72)。运行时依赖 i18n-js(随本包安装,无需单独声明)。
本模块支持 Autolink。harmony.alias 为 react-native-i18n,业务代码从该原库名导入,而不是 @hxa-rn/react-native-i18n。
HAR 路径:harmony/i18n.har。
使用说明
import I18n, { getLanguages } from 'react-native-i18n';
export async function setupI18n() {
I18n.translations = {
en: {
greeting: 'Hello',
items: { one: '{{count}} item', other: '{{count}} items' },
},
zh: {
greeting: '你好',
items: { one: '{{count}} 个项目', other: '{{count}} 个项目' },
},
};
I18n.defaultLocale = 'en';
I18n.fallbacks = true;
const langs = await getLanguages();
const greeting = I18n.t('greeting');
const items = I18n.pluralize(2, 'items');
return { langs, greeting, items };
}接口文档
| API | 描述 | 参数 | 返回值 | HarmonyOS 支持 |
|-----|------|------|--------|----------------|
| getLanguages() | 获取设备首选语言 tag 列表 | 无 | Promise<string[]> | ✅ 完全支持 |
| languages | 首选语言常量数组 | 无 | string[] | ✅ 完全支持 |
| I18n.locale | 当前语言 | string | string | ✅ 完全支持 |
| I18n.t(scope) | 按 locale 翻译 | scope, options? | string | ✅ 完全支持 |
| I18n.pluralize(count, scope) | 复数翻译 | count, scope, options? | string | ✅ 完全支持 |
| I18n.fallbacks | 语言回退开关 | boolean | boolean | ✅ 完全支持 |
鸿蒙通过 i18n.System.getPreferredLanguageList() 返回 BCP-47 tag(如 zh-Hans-CN)。
快速验证(运行 Example)
前置条件
| 依赖 | 版本要求 | |------|----------| | Node.js | >= 18 | | DevEco Studio | 5.0+ | | HarmonyOS SDK | API 12+ |
运行步骤
1. 克隆仓库
git clone https://gitcode.com/hxa-rn/react-native-i18n.git
cd react-native-i18n
git checkout br_rnoh0.722. 安装仓库开发依赖
npm install --legacy-peer-depsExample 已改为从 npm 公仓安装 @hxa-rn/[email protected],不再使用本地 file:../xxx.tgz,运行 Example 不必再执行 npm pack。
3. 进入 example 目录,安装依赖
cd example # 或 example_auto
npm install --legacy-peer-deps4. 生成 JS Bundle
npm run dev产物:harmony/entry/src/main/resources/rawfile/bundle.harmony.js
5. 用 DevEco Studio 打开鸿蒙工程
- 打开 DevEco Studio
- 选择
example/harmony(或example_auto/harmony)目录 - 等待 Sync 完成
6. 编译并运行 HAP
在 DevEco Studio 中点击运行按钮,将 HAP 安装到设备/模拟器。
注意:Example 中已预置插件依赖和 Package 注册,无需手动配置 Link。
约束与限制
兼容性
- 鸿蒙 SDK:API 12+
- 上游 RN SDK:0.72+
- React Native / RNOH:0.72+
- DevEco Studio:5.0+
权限
- 无额外系统权限
使用限制
- 系统语言变更无实时事件推送。
- 建议开启
I18n.fallbacks = true支持变体回退。
开源license
本项目基于 MIT 协议,详见 LICENSE 文件。
问题反馈渠道
使用问题请在 AtomGit 提交 Issue。也可在 GitCode 仓库反馈:
https://gitcode.com/hxa-rn/react-native-i18n
https://gitcode.com/hxa-rn/react-native-i18n/issues
