react-i18next,从 props 添加资源

react-i18next, add resources from props

我有组件的回购和主应用程序的回购。我在 repo 中使用组件实现了 i18next,当我在这个 repo 中有一个 i18n 配置文件时(或者当我通过应用程序 repo 的 props 传递它时)它工作正常。但是当我尝试仅从主应用程序发送 "resource" 部分并将其替换为组件的配置文件时,我遇到了问题。我尝试克隆 i18n 实例并设置资源,但它不起作用。 这是我的配置文件: i18n.js

import i18n from 'i18next';
import LngDetector from 'i18next-browser-languagedetector';
import { reactI18nextModule } from 'react-i18next';

i18n
  .use(LngDetector)
  .use(reactI18nextModule)
  .init({
    detection: {
      order: ['cookie', 'localStorage'],
      lookupLocalStorage: 'i18n_lang',
      lookupCookie: 'i18n_lang',
      caches: ['localStorage'],
    },
    load: 'current',
    fallbackLng: 'en',

    ns: ['components'],
    defaultNS: 'components',

    keySeparator: false,
    interpolation: {
      escapeValue: false,
      formatSeparator: ',',
        },
        react: {
          wait: true,
     },
  });

export default i18n;

resources.js 文件(我一开始尝试使用 resources 密钥,但它仍然不起作用):

import * as en from './en.json';
import * as de from './de.json';

export default {
  en: {
    components: en,
  },
  de: {
    components: de,
  },
};

现在我尝试了这样的事情:

import * as langs from './resources';

const newI18 = i18n.cloneInstance({ resources: langs });

const i18ProviderDecorator = (storyFn) => (
  <I18nextProvider i18n={newI18}>
    { storyFn() }
  </I18nextProvider>

当我通过带有资源的 props 传递 i18n.js 时,它工作完美,但我想从主应用程序中删除 i18next 并将其仅保留在组件中。 问候

a i18next 克隆实例使用与原始实例相同的存储 -> 并且不会再次初始化 -> 因此以这种方式传递资源不起作用:https://github.com/i18next/i18next/blob/master/src/i18next.js#L308

创建一个新实例 i18n.createInstance 或使用 i18n.addResourceBundle 将资源传递给克隆:https://www.i18next.com/api.html#addresourcebundle