reactjs - 从多个后端加载翻译

标签 reactjs i18next

我有使用react-i18next的React应用程序,翻译存储在两个位置。一组存储在应用程序本地的文件夹中,其余翻译来自远程 API。

我正在努力将两组数据加载到应用程序中。使用 i18next-chained-backend 插件,它似乎只在第一个后端不加载翻译时提供后备,我似乎无法将其配置为加载两组翻译。

在基于 React 的应用程序中包含多个来源的翻译的最佳方法是什么?

最佳答案

我能够从不同的地方加载翻译,而无需使用任何依赖项。 (仅适用于 npm 包“react-i18next”和“i18next”)

这些是我遵循的步骤:

  1. i18n.js 中,设置客户端区域设置定义。
  2. 提供命名空间列表,以在同一文件中的 ns 键中查找翻译键。

    Say the namespaces are ['translations', 'bkdynamic']

  3. 在您的主 React 组件中,从 API 端点获取翻译。

    In the given sandbox, API call is a mock which fetches sampleTx.json from your public/ directory. This could be replaced to an actual endpoint which returns a JSON.

  4. 使用 i18next.addResourceBundle API 加载您所需语言的翻译。

    Load the newly fetched translations in namespace bkdynamic for the selected language. Note: While doing i18next.addResourceBundle call, set deep param to true; so that new translations are extended.

  5. 其余翻译 API 相同。

这里是实时沙箱 - https://codesandbox.io/embed/i18next-muliple-files-p565v

  • 本地翻译 - “你好”、“早上好”
  • 从另一个端点加载的翻译 - “Good”

希望这有帮助。

关于reactjs - 从多个后端加载翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884796/

相关文章:

javascript - React fetch Firebase 获取唯一键值

node.js - NextJS API 未发布到外部域

javascript - 使用 RequireJS-i18next-plugin 时的 i18next 特殊功能

jquery 移动按钮样式在本地化时丢失

reactjs - 通过扩展排版在 React 中使用 Material UI 进行 i18n 本地化?

javascript - state.getStore() 或 mapStateToProps - React.js/Redux

reactjs - 如何检查 create-react-app 项目是否已弹出?

javascript - setState 不是一个函数

javascript - 如何使用 i18next 翻译部分 HTML 文本?

javascript - 获取 i18next 未定义