我有使用react-i18next的React应用程序,翻译存储在两个位置。一组存储在应用程序本地的文件夹中,其余翻译来自远程 API。
我正在努力将两组数据加载到应用程序中。使用 i18next-chained-backend 插件,它似乎只在第一个后端不加载翻译时提供后备,我似乎无法将其配置为加载两组翻译。
在基于 React 的应用程序中包含多个来源的翻译的最佳方法是什么?
最佳答案
我能够从不同的地方加载翻译,而无需使用任何依赖项。 (仅适用于 npm 包“react-i18next”和“i18next”)
这些是我遵循的步骤:
- 在
i18n.js
中,设置客户端区域设置定义。 - 提供命名空间列表,以在同一文件中的
ns
键中查找翻译键。Say the namespaces are ['translations', 'bkdynamic']
- 在您的主 React 组件中,从 API 端点获取翻译。
In the given sandbox, API call is a mock which fetches
sampleTx.json
from yourpublic/
directory. This could be replaced to an actual endpoint which returns a JSON. - 使用
i18next.addResourceBundle
API 加载您所需语言的翻译。Load the newly fetched translations in namespace
bkdynamic
for the selected language. Note: While doingi18next.addResourceBundle
call, setdeep
param totrue
; so that new translations are extended. - 其余翻译 API 相同。
这里是实时沙箱 - https://codesandbox.io/embed/i18next-muliple-files-p565v
- 本地翻译 - “你好”、“早上好”
- 从另一个端点加载的翻译 - “Good”
希望这有帮助。
关于reactjs - 从多个后端加载翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884796/