reactjs - i18next 如何加载翻译?
问题描述
我正在尝试在我的应用程序中添加翻译,但我找不到使 i18next 工作的方法。
这里是 i18n.ts
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import * as en from './i18n/en.json';
import * as jp from './i18n/jp.json';
i18n
.use(initReactI18next)
.init({
resources: {
en,
jp
},
lng: "en",
fallbackLng: "en",
keySeparator: ".",
debug: true,
interpolation: {
escapeValue: false
}
});
export default i18n;
然后,我将其导入索引文件的第二行。
日志是:
i18next: languageChanged en i18next.js:27
i18next: 初始化 {debug: true, initImmediate: true, ns: Array(1), defaultNS: Array(1), fallbackLng: Array(1), ...} projectSelector.tsx:16 I18n {observers: {...}, options: {...},服务:{...},记录器:记录器,模块:{...},...} i18next.js:27
i18next::translator: missingKey en 翻译 PROJECT.CREATE_PROJECT.DEFAULT_PJ_NAME
翻译看起来像这样
{
"PROJECT": {
"CREATE_PROJECT" : {
"DEFAULT_PJ_NAME" : "Default"
}
}
}
解决方案
你走在一条好路上,你只需要添加翻译来标记 i18next 的翻译
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import en_translate from './i18n/en.json';
import jp_transltate from './i18n/jp.json';
i18n
.use(initReactI18next)
.init({
resources: {
en:{
translation: en_translate
},
jp:{
translation: jp_transltate
}
},
lng: "en",
fallbackLng: "en",
keySeparator: ".",
debug: true,
interpolation: {
escapeValue: false
}
});
export default i18n;
使用 Hook 在功能组件中添加翻译
import React from 'react';
// the hook
import { useTranslation } from 'react-i18next';
function MyComponent () {
const { t, i18n } = useTranslation();
return <h1>{t('PROJECT.CREATE_PROJECT.DEFAULT_PJ_NAME')}</h1>
}
您可以查看i18next 快速入门指南以了解不同的实现,它得到了很好的解释
推荐阅读
- node.js - 当我尝试直接在 package.json 文件中执行脚本时,nodejs __dirname 是一个点
- css - 在移动设备上滚动下拉菜单不起作用
- python - 如何更改所有包含数字的字符串单元格以在熊猫中一次全部浮动?
- angular - 如何获取未更新的响应式表单数据?
- c - 为什么共享库必须是位置独立的,而静态库不是?
- c++ - 将输入流转换为双向量
- elasticsearch - Kibana {"statusCode":403,"error":"Forbidden","message":"Forbidden"}
- javascript - 为什么递归函数中特别需要“null”?
- javascript - jQuery按钮切换文本在onlick上不起作用
- python - 如何在 Python 中将嵌套字典的值与不同数量的键相乘?