首页 > 解决方案 > react native expo i18n 中缺少翻译

问题描述

因此,在我的应用程序中,我需要根据手机本身的配置方式来使用西班牙语和英语的文本。无论如何,经过大量研究,我所做的每一次尝试都得出了相同的结论,即[缺少'en.Messages'翻译]。有人可以告诉我我错过了什么或做错了什么吗?

APP.JS

  import { loadLocale } from "./i18n";

  const init = async () => {
    await loadLocale();
  };

  useEffect(() => {
    init();
  }, []);

i18n.js

import * as Localization from "expo-localization";
import i18n from "i18n-js";

i18n.defaultLocale = "en";
i18n.locale = "en";
i18n.fallbacks = true;

export const loadLocale = async () => {
  for (const locale of Localization.locales) {
    if (i18n.translations[locale.languageCode] !== null) {
      i18n.locale = locale.languageCode;
      switch (locale.languageCode) {
        case "en":
          import("./translations/en.json").then((en) => {
            i18n.translations = { en };
          });
          break;
        default:
        case "es":
          import("./translations/es.json").then((es) => {
            i18n.translations = { es };
          });
          break;
      }
      break;
    }
  }
};

export default i18n;

翻译文件夹

inside the translations folder are 2 files call en.json / es.json
{
    "Messages": "Messages!",
}

消息.js

import i18n from "../i18n";

<Text>{i18n.t("Messages")}</Text>

标签: reactjsreact-nativelocalizationtranslationi18next

解决方案


在加载语言环境之前尝试设置 defaultLocale。

import { loadLocale } from "./i18n";

     i18n.defaultLocale = "en";
     i18n.locale = "en";
     i18n.fallbacks = true;

  const init = async () => {
    await loadLocale();
  };

  useEffect(() => {
    init();
  }, []);

推荐阅读