react-i18next,从props添加资源

时间:2018-02-13 12:43:22

标签: javascript reactjs i18next react-i18next

我有主要应用程序的组件和repo的repo。我在repo中使用组件实现了i18next,当我在这个repo中有一个i18n配置文件时(或者当我通过app repo中的props传递它时)它工作正常。但是当我尝试仅从主应用程序发送“资源​​”部分并将其替换为组件中的配置文件时,我遇到了问题。我试图克隆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文件(我在开始时尝试使用资源键,但它仍然不起作用):

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>

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

1 个答案:

答案 0 :(得分:1)

i18next克隆实例使用与原始实例相同的商店 - &gt;并且不会再次初始化 - &gt;所以以这种方式传递资源不起作用:https://github.com/i18next/i18next/blob/master/src/i18next.js#L308

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