You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置React Native的index.js文件以支持乌尔都语、英语、荷兰语等多语言

React Native 多语言适配配置教程

1. 依赖安装

我们用 react-native-localize(检测系统语言)+ i18n-js(国际化翻译)的常用组合实现,先执行安装命令:

npm install i18n-js react-native-localize
# 如果你用yarn的话
yarn add i18n-js react-native-localize
# iOS端需要执行pod安装
cd ios && pod install && cd ..

如果需要切换语言后立即生效,可额外安装react-native-restart。

2. 语言文件配置

新建src/i18n目录,存放各语言的翻译文件:

  • en.json(英语)
{
  "welcome": "Welcome",
  "settings": "Settings",
  "changeLanguage": "Change Language"
}
  • nl.json(荷兰语)
{
  "welcome": "Welkom",
  "settings": "Instellingen",
  "changeLanguage": "Taal wijzigen"
}
  • ur.json(乌尔都语)
{
  "welcome": "خوش آمدید",
  "settings": "ترتیبات",
  "changeLanguage": "زبان تبدیل کریں"
}

同目录下新建i18n.js全局配置文件:

import I18n from 'i18n-js';
import * as RNLocalize from 'react-native-localize';
import en from './en.json';
import nl from './nl.json';
import ur from './ur.json';

// 注册所有支持的语言
I18n.translations = {
  en,
  nl,
  ur,
};

// 匹配系统首选语言,匹配失败默认用英语
const fallbackLang = { languageTag: 'en', isRTL: false };
const { languageTag, isRTL } = RNLocalize.findBestAvailableLanguage(Object.keys(I18n.translations)) || fallbackLang;

I18n.defaultLocale = 'en';
I18n.locale = languageTag;
I18n.fallbacks = true;

export const isCurrentLanguageRTL = isRTL;
export default I18n;

3. 入口文件index.js配置

核心要做i18n初始化、RTL布局适配(针对乌尔都语这类从右到左的语言):

import { AppRegistry, I18nManager } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import I18n, { isCurrentLanguageRTL } from './src/i18n/i18n';

// 强制适配当前语言的RTL布局
I18nManager.forceRTL(isCurrentLanguageRTL);

// 可选:如果RTL状态发生变化自动重启APP生效,不需要可删除
if (I18nManager.isRTL !== isCurrentLanguageRTL) {
  require('react-native-restart').Restart();
}

AppRegistry.registerComponent(appName, () => App);

4. 业务中使用

普通文案调用

在任意组件中直接引入i18n实例调用翻译方法即可:

import I18n from './src/i18n/i18n';

const Demo = () => {
  return <Text>{I18n.t('welcome')}</Text>
}

手动切换语言

const switchLanguage = (langCode) => {
  I18n.locale = langCode;
  const isRTL = langCode === 'ur';
  I18nManager.forceRTL(isRTL);
  // 切换后重启APP生效
  require('react-native-restart').Restart();
}

// 调用示例:切换到乌尔都语 switchLanguage('ur'),切换到荷兰语 switchLanguage('nl')

注意事项

  • 所有文案不要硬编码在组件中,统一存放在对应语言的json文件内,新增语言仅需新增json文件并在i18n.js的translations中注册即可
  • 乌尔都语为RTL语言,RN的flex布局会自动适配翻转,大部分场景无需额外修改样式,特殊布局可根据isCurrentLanguageRTL状态单独适配

内容的提问来源于stack exchange,提问作者Dian Us Suqlain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:57:03