react native国际化

1,900 阅读1分钟

1./js/i18n/en.json

{
  "login": {
    "email": "Please enter your email",
    "password": "Please input a password",
    "login": "LOGIN"
  },
  "tab": {
    "home": "Home",
    "list": "List",
    "account": "Account"
  },
  "home": {
    "jump": "jump to PageSetting"
  },
  "list": {
    "jump": "jump to PageDetail"
  },
  "account": {
    "logout": "Logout"
  }
}

2./js/i18n/zh.json

{
  "login": {
    "email": "邮箱",
    "password": "密码",
    "login": "登录"
  },
  "tab": {
    "lesson": "课程",
    "book": "图书",
    "learn": "学习",
    "parental": "我的"
  },
  "home": {
    "jump": "跳转到设置页"
  },
  "list": {
    "jump": "跳转到详情页"
  },
  "account": {
    "logout": "退出登录"
  },
  "warn": {
    "error": "发生错误,请重试"
  }
}

3./js/i18n/index.js

import * as RNLocalize from 'react-native-localize';
import { I18nManager } from 'react-native';
import I18n from 'i18n-js';

import en from '~/i18n/en.json';
import zh from '~/i18n/zh.json';

I18nManager.allowRTL(false);

const locales = RNLocalize.getLocales();
if (Array.isArray(locales)) {
  I18n.locale = locales[0].languageCode;
}
I18n.fallbacks = true;
I18n.translations = {
  en,
  zh,
};

export default I18n;

4.使用

import i18n from '~/i18n';

Toast.show(i18n.t('warn.error'))