javascript - React-i18next,从 props 添加资源

标签 javascript reactjs i18next react-i18next

我有带有组件的存储库和带有主应用程序的存储库。我在带有组件的存储库中实现了 i18next,当我在此存储库中有 i18n 配置文件时(或者当我通过应用程序存储库中的 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 文件(我一开始就尝试使用 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 并将其仅保留在组件中。 问候

最佳答案

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

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

关于javascript - React-i18next,从 props 添加资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48767121/

相关文章:

javascript - 如何使用 jQuery 更改 CSS?

javascript - React,如何从文件夹index.js导入组件

reactjs - 移动平台不支持 react-draggable 吗?

javascript - 无法读取未定义的属性 'toResolveHierarchy'

node.js - 在不在 App.js 中的函数中访问 i18next Translation

javascript - 如何动态地将数据从一个html页面添加到另一个html页面的列表中

javascript - 密码 - 大写字符 JavaScript

javascript - Knockout 在刷新之前不会渲染客户端选择框 (Breeze.js)

javascript - 92% block Assets 优化 - webpack

node.js - 如何制作多语言 Dialogflow webhook/fulfillment?