我目前正在使用 Material UI 开发一个 React 项目。我正在我的项目中实施 React i18n。我是按照react-18next官方文档的init文件来配置i18n的。但是,当我尝试使用 useTranslation() 挂钩的“t”函数时,当我将鼠标悬停在“t”上时,它会显示
const t: TFunction<"translation", undefined, "translation">
。一直在这里搜索相关问题,但仍然找不到解决方案。谁能帮忙?非常感谢。
我的 i18n.js 代码:
import React from "react";
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import enLocales from './enUS.json'
import znHKLocales from './zhHK.json'
import zhCNLocales from './zhCN.json'
import LanguageDetector from 'i18next-browser-languagedetector';
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.use(LanguageDetector)
.init({
resources: {
enUS: { translation: { enLocales } },
zhHK: { translation: { znHKLocales } },
zhCN: { translation: { zhCNLocales } },
},
lng: localStorage.getItem('i18nextLng') || 'enUS',
fallbackLng: "enUS",
saveMissing: false,
returnObjects: true,
debug: false,
interpolation: {
escapeValue: false
},
});
export default i18n;
我的 locales.js 代码(我把所有相关的语言函数放在这里):
import { useContext } from "react";
import React from 'react';
import { useTranslation } from 'react-i18next';
import LanguageContext from '../context/LanguageContext'
import { enUS, zhHK, zhCN } from '@mui/material/locale';
const useLocales = () => {
const context = useContext(LanguageContext);
const { i18n, t } = useTranslation();
const currentLangStorage = localStorage.getItem('i18nextLng');
const LANGS = [
{
label: t('English'),
mappingValue: 'enUS',
value: 'enUS',
systemValue: enUS,
},
{
label: t('Chinese (Hong Kong)'),
mappingValue: 'zhHK',
value: 'zhHK',
systemValue: zhHK,
},
{
label: t('Chinese (Simplified)'),
mappingValue: 'zhCN',
value: 'zhCN',
systemValue: zhCN,
},
];
const handleChangeLang = (newLang) => {
console.log('newlang ', newLang)
i18n.changeLanguage(newLang.value);
context.setLangMode(newLang.systemValue);
}
return {
onChangeLang: handleChangeLang,
allLang: LANGS,
t, //I export the t here, it is imported from the useTranslation() hook above
enUS,
}
}
export default useLocales;
我在反应组件中更改语言的代码:
import * as React from 'react';
import { Container, Box, Typography, Button } from '@mui/material';
import useLocales from '../hooks/useLocales';
const Home = () => {
const { t } = useLocales();
return (
<Container maxWidth="md">
<Typography>{t("Home")}</Typography>
</Container>
)
}
export default Home;
我的 index.js 代码:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
import './locales/i18n'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
reportWebVitals();
我的包.json:
"i18next": "^22.4.14",
"i18next-browser-languagedetector": "^7.0.1",
"i18next-http-backend": "^2.2.0",
当我控制台记录我的 handleChangeLang() 函数时,语言更改成功。就在我将鼠标悬停在“t”上时,它显示“const t: TFunction<"translation", undefined, "translation">”。