首页 > 解决方案 > i18next 如何加载翻译?

问题描述

我正在尝试在我的应用程序中添加翻译,但我找不到使 i18next 工作的方法。

这里是 i18n.ts

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import * as en from './i18n/en.json';
import * as jp from './i18n/jp.json';

i18n
  .use(initReactI18next)
  .init({
    resources: {
      en,
      jp
    },
    lng: "en",
    fallbackLng: "en",
    keySeparator: ".",
    debug: true,
    interpolation: {
      escapeValue: false
    }
});

export default i18n;

然后,我将其导入索引文件的第二行。

日志是:

i18next: languageChanged en i18next.js:27

i18next: 初始化 {debug: true, initImmediate: true, ns: Array(1), defaultNS: Array(1), fallbackLng: Array(1), ...} projectSelector.tsx:16 I18n {observers: {...}, options: {...},服务:{...},记录器:记录器,模块:{...},...} i18next.js:27

i18next::translator: missingKey en 翻译 PROJECT.CREATE_PROJECT.DEFAULT_PJ_NAME

翻译看起来像这样

{
  "PROJECT": {
    "CREATE_PROJECT" : {
      "DEFAULT_PJ_NAME" : "Default"
    }
  }
}

标签: reactjsi18nextreact-i18next

解决方案


你走在一条好路上,你只需要添加翻译来标记 i18next 的翻译

import i18n from "i18next";
import { initReactI18next } from "react-i18next";

import en_translate from './i18n/en.json';

import jp_transltate from './i18n/jp.json';

i18n
  .use(initReactI18next)
  .init({
    resources: {
      en:{
            translation: en_translate              
        },
      jp:{
            translation: jp_transltate              
        }
    },
    lng: "en",
    fallbackLng: "en",
    keySeparator: ".",
    debug: true,
    interpolation: {
      escapeValue: false
    }
});

export default i18n;

使用 Hook 在功能组件中添加翻译

import React from 'react';

// the hook
import { useTranslation } from 'react-i18next';

function MyComponent () {
  const { t, i18n } = useTranslation();
  return <h1>{t('PROJECT.CREATE_PROJECT.DEFAULT_PJ_NAME')}</h1>
}

您可以查看i18next 快速入门指南以了解不同的实现,它得到了很好的解释


推荐阅读