React Native 如何设置i18n.js回退语言?

d4so4syb  于 2023-04-22  发布在  React
关注(0)|答案(1)|浏览(151)

我使用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"),
};

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

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配置!

bihw5rsg

bihw5rsg1#

您必须设置i18n.enableFallback = true并使用i18n.defaultLocale = "en"设置默认区域设置。它将回退到默认值。
这是一个最小的示例(将Localization.locale交换为您正在使用的任何内容):

import { I18n } from 'i18n-js';

const translations = {
  en: { welcome: 'Hello'},
  de: { welcome: 'Hallo'},
  ja: { welcome: 'こんにちは'},
};

const i18n = new I18n(translations);
i18n.locale = Localization.locale;
i18n.enableFallback = true;
i18n.defaultLocale = "en";

基于Github的问题:https://github.com/fnando/i18n-js/issues/525

相关问题