【发布时间】:2023-08-09 19:49:01
【问题描述】:
我需要为 react js 项目实现翻译。
在我的项目src/locale/i18n.js文件中
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-http-backend';
i18n
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(Backend)
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
debug: true,
fallbackLng: 'en',
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
});
export default i18n;
我将此文件导入 index.js
import './locales/i18n'
ReactDOM.render(
<React.StrictMode>
<Suspense fallback="Loading...">
<App />
</Suspense>
</React.StrictMode>,
document.getElementById('root')
);
在我的 app.js 中
import { useTranslation, Trans } from 'react-i18next';
function App() {
const { t, i18n } = useTranslation();
const changeLanguage = (lang) => {
i18n.changeLanguage(lang)
}
return (
<div className="App">
{t('description.part2')}
<button onClick={() => changeLanguage('en')}>EN</button>
<button onClick={() => changeLanguage('si')}>SI</button>
</div>
);
}
另外,我的翻译键放在public/locales/en/transalation.json 和public/locales/si/transalation.json
此设置运行良好。但我需要从后端 API 加载我的翻译。 它有一些 JSON 文件,这是 URL 格式
BASEURL/locales/Language/NameSpace.json
它的命名空间很少,例如
报告
常见
仪表板
所以如果对常见的 NameSpace 运行英文翻译,
BASEURL/locales/Language/NameSpace.json
服务器返回一个这样的 JSON 对象
{
"com:search":"search",
"com:logout":"logout"
}
如何一次调用这些 API 端点并将其提供给 i18n 实例?所以我可以像这样在项目的任何地方使用这些翻译键
<h2>{t("common:com-description")}</h2>
【问题讨论】:
-
我想这会更好,如果你写脚本来下载翻译到文件夹
public/locales/si/transalation.json(()=> if (!fs.existsSync(./public/locales)) fs.mkdirSync(./public/locales);
标签: javascript reactjs internationalization i18next react-i18next