0

我正在使用i18n-js库。

为了设置其配置,我正在执行以下操作:

export function setI18nConfig(locale = undefined) {
  // Fallback if no available language fits
  const fallback = DEFAULT_APP_LANGUAGE;
  const language =
    APP_LANGUAGES.find((language) => language.locale === locale) ?? fallback;

  const { locale: _locale, isRTL } = language;

  // Clear the translation cache
  translate.cache.clear();

  // Update the layout direction
  I18nManager.forceRTL(isRTL);

  // Set the i18n-js config
  i18n.locale = _locale;
  i18n.translations = { [_locale]: translationGetters[_locale]() };

  // Set moment config
  moment.locale(_locale);

  // Return the appropiate locale
  return _locale;
}

如您所见,为了设置翻译字典,我将其称为 getter:

 export const translationGetters = {
  en: () => require("../../../assets/languages/en/translations.json"),
  es: () => require("../../../assets/languages/es/translations.json"),
  fr: () => require("../../../assets/languages/fr/translations.json"),
  it: () => require("../../../assets/languages/it/translations.json"),
  pt: () => require("../../../assets/languages/pt/translations.json"),
};

为了建立备用语言,我只是想在我的应用程序语言数组中找到给定的语言环境(函数参数)。

export const APP_LANGUAGES = [
  {
    name: "English",
    locale: "en",
    isRTL: false,
  },
  {
    name: "French",
    locale: "fr",
    isRTL: false,
  },
  {
    name: "Italian",
    locale: "it",
    isRTL: false,
  },
  {
    name: "Portuguese",
    locale: "pt",
    isRTL: false,
  },
  {
    name: "Spanish",
    locale: "es",
    isRTL: false,
  },
];

如果它不在列表中,那么我使用 DAFAULT_APP_LANGUAGE 作为翻译。

export const DEFAULT_APP_LANGUAGE = APP_LANGUAGES[0];

这是设置 i18n.js 后备的典型或正确方法吗?

没有任何简单的方法可以做到这一点吗?

我的意思是,类似:

  i18n.fallbackLanguage = "en";
  i18n.locale = locale;
  i18n.translations = {
     [locale]: translationGetters[locale](), 
     [fallbackLanguage]: translationGetters[fallbackLanguage]() 
  };

注意:我还需要为后备设置 isRTL 配置!

4

0 回答 0