从不同的 JSON 文件读取 i18n [React-i18next]

Read i18n from different JSON files [React-i18nnext]

我是 react-i18nnext 库的新手。我尝试将我的翻译分成文件,这样每一页都有一个单独的 JSON 文件,而不是一个文件。

我对如何执行 this guide 中的以下步骤感到困惑:


我如何尝试从其他文件实现 i18n:

我正在使用以下代码调用默认 translate.json 文件:

<h1>{t('title')}</h1>

但是我想调用不同的文件,所以我必须按照指南使用:

<h1>{t('test:title')}</h1>

如果我使用文件 translation.json - 一切正常,但如果我使用文件的另一个名称 - 它会失败并出现错误:

i18next::translator: missingKey en test title title

我的应用程序中的文件:


其他代码

我遵循了图书馆官方页面上的 "Step by Step" 指南。

这是我的 i18n.js 文件:

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

import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
// not like to use this?
// have a look at the Quick start guide
// for passing in lng and translations on init


const languages = ['en', 'de', 'et'];

i18n
    /*
     load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
     learn more: https://github.com/i18next/i18next-http-backend
    */
    .use(Backend)
    /*
     detect user language
     learn more: https://github.com/i18next/i18next-browser-languageDetector
    */
    .use(LanguageDetector)
    /*
     pass the i18n instance to react-i18next.
    */
    .use(initReactI18next)
    /*
     init i18next
     for all options read: https://www.i18next.com/overview/configuration-options
    */
    .init({
        lng:"ee",
        fallbackLng: 'et', // use et if detected lng is not available
        saveMissing: true, // send not translated keys to endpoint
        debug: true,
        whitelist: languages,

        // backend: {
        //     // for all available options read the backend's repository readme file
        //     loadPath: '/locales/{{lng}}/{{ns}}.json'
        // },

        react: {
            useSuspense: false
        }
    })


export default i18n;

为了更好地了解,我将我的代码添加到 codesandbox:

为了在同一个页面中使用多个命名空间,需要在调用时指定useTranslation

export default function App() {
  const [t] = useTranslation(["translation", "customFile"]);
  // ---------------------------------------------^

  return (
    <div className="App">
      <button onClick={() => changeLanguageOnClick("en")}>English</button>
      <button onClick={() => changeLanguageOnClick("de")}>German</button>
      <h1>{t("title")}</h1>
      <h2>{t("customFile:title")}</h2>
    </div>
  );
}

这是它的样子: https://codesandbox.io/s/intelligent-shockley-q588u?file=/src/App.js:243-304