reactjs - react-i18next - 初始化后如何向 i18n 添加后端?
问题描述
我希望我的 i18n 延迟加载翻译文件,并且从文档中,这样做似乎很简单 - 添加.use(backend)
和import backend from "i18next-http-backend"
.
唯一的问题是我在提供的 i18n 实例中已经在我的组织的内部存储库中定义为 UI 库(我必须使用它),它只公开了一种为您初始化 i18n 实例的方法 - 这不会有任何规定.use(backend)
,现在我被困在如何将其添加到代码中。
这是库代码 -
...
export const getDefaultI18nextInstance = (resources) => {
i18n
.use(AlphaLanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
// have a common namespace used around the full app
ns: [
'translations',
'common'
],
nsMode: 'fallback',
defaultNS: 'translations',
// debug: (process.env.NODE_ENV && process.env.NODE_ENV === 'production') ? false : true,
debug: true,
interpolation: {
escapeValue: false, // not needed for react!!
},
resources: resources || null,
react: {
wait: true
}
});
Object.keys(translations).forEach(lang => {
Object.keys(translations[lang]).forEach(namespace => {
i18n.addResourceBundle(lang, namespace, translations[lang][namespace], true, true)
})
});
return i18n;
}
export default {
getDefaultI18nextInstance,
translations,
t
};
...
我尝试在我的 index.js 文件中使用类似这样的东西 <I18nextProvider i18n={i18n.getDefaultI18nextInstance().use(backend)}>
,但后来我得到了错误
i18next::backendConnector:没有通过 i18next.use 添加后端。不会加载资源。
仅供参考,我的语言环境位于projectRoot/locales/{lang}/translation.json
.
解决方案
您可以使用i18n.cloneInstance(options, callback)
并传递您的后端配置 as options
,它将合并您的 ui lib 具有的所有选项,并返回一个新的 i18next 实例,该实例将能够获取。
import HttpApi from 'i18next-http-backend';
const original = getDefaultI18nextInstance({});
export const i18n = original
.cloneInstance({
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
},
})
.use(HttpApi);
推荐阅读
- android - OnBackPressedCallback 未在底部工作表对话框片段中调用
- javascript - 如果我不使用 import/require,webpack babel 如何复制转译文件
- javascript - 使用 jQuery 实时更新 HTML
- python - 从 Spark / PySpark 中不一致数组的数据帧列中比较和删除元素
- javascript - 我们如何通过比较 Markdown 语言中的单词来包含一个搜索栏以在同一页面内导航?
- angular - “无法解析 ApplicationModule 的所有参数:(?)。” 使用 Angular SSR 运行时
- javascript - 无法在角度表格的 td 标记内加粗特定单词
- php - yii2如何编写sql查询
- excel - VBA复制功能随机失败
- oracle - 如何维护 Sonar 表 PROJECT_MEASURES 的清理