首页 > 解决方案 > 组件渲染时 i18n 未初始化

问题描述

在我的 expo 应用程序中,我想使用 i18n-js 国际化字符串。

问题是,它是异步初始化的,组件的渲染速度更快。出于这个原因,我得到“缺少 xy 翻译”的结果。如何实现渲染前的初始化?

我发布了我的 i18n 组件。计划只是导入那个并使用它的 funktion t()。

import * as Localization from 'expo-localization';
import i18n from 'i18n-js';
i18n.translations = {
  en: {
    "hello": "Hello World!"
  , "signin": "Sign In"
  , "wrongPassword": "Wrong Password"
  , "Please enter a valid email address": "Please enter a valid email address"
  , "Username contains unallowed characters": "Username contains unallowed characters"
  , "No Acount? Sign Up": "No Acount? Sign Up"
  , "Password": "Password"
  , "Password is too short. Must be greater than 6 characters": "Password is too short. Must be greater than 6 characters"
  , "Passwords do not match": "Passwords do not match"
  , "Email address": "Email address"
  , "Enter password again":"Enter password again"
  , "Password Confirm":"Password Confirm"
  , "SIGN UP":"Sign Up"
  , "Already Signed Up? Sign In": "Already Signed Up? Sign In"
  , "You":"You"
  , "Your running games":"Your running games"
  , "New Game":"New Game"
  , "me": "me"
},
  de: {
    "hello": "Hello World!"
  , "signin": "Einloggen"
  , "wrongPassword": "Falsches Passwort"
  , "Please enter a valid email address": "Bitte benutzen Sie eine valide Email Adresse"
  , "Username contains unallowed characters": "Benutzername enthält unerlaubte Zeichen"
  , "No Acount? Sign Up": "Kein Konto? Registrieren!"
  , "Password": "Passwort"
  , "Password is too short. Must be greater than 6 characters": "Passwort zu kurz. Bitte mindestens 6 Zeichen"
  , "Passwords do not match": "Passwörter stimmen nicht überein"
  , "Email address": "Email Adresse"
  , "Enter password again":"Passwort nochmal eingeben"
  , "Password Confirm":"Passwort bestätigen"
  , "SIGN UP":"Registrieren"
  , "Already Signed Up? Sign In":"Bereits registriert? Einloggen!"
  , "You":"Du"
  , "Your running games":"Deine laufenden Spiele"
  , "New Game":"Neues Spiel"
  , "me": "ich"
  }
};
// Set the locale once at the beginning of your app.
i18n.locale = Localization.locale;
i18n.fallbacks = true;

const t = (text) => {
   return i18n.t(text);
};

export default t;

标签: react-nativeinternationalizationexpo

解决方案


由于我无法直接解决上述问题,我的解决方法是实现我自己的功能。就我而言,我只提供两种语言,所以很简单。如果它也能帮助其他人,我很高兴:

import * as Localization from 'expo-localization';

import en from './en.json';
import de from './de.json';

// Set the locale once at the beginning of your app.
const locale = Localization.locale.split('-')[0];

const t = (key) => {
   var v = null;
   if (locale == 'de') {
       v = de[key];
   }
   if (locale == 'en' || v == null)
      v = en[key]
   if (v == null)
      v='t('+key+')';
   return v;
};

export default t;

推荐阅读