我在 vite/react 项目上工作,我已经安装了 i18next 包来处理翻译,但是翻译没有出现,而是出现了翻译的键。 这是位于 src 目录中的 mt 18n.js 文件:
import i18n from 'i18next'
import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
},
lng: localStorage.getItem('i18nextLng') || 'en',
fallbackLng: 'en',
whitelist: ['en', 'ar'],
react: {
wait: true,
},
})
export default i18n
这是我的 main.jsx 文件形式,将 18n 包装为提供者:
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter as Router } from 'react-router-dom'
import App from './App.jsx'
import './index.css'
import i18n from './i18n.js'
import { I18nextProvider } from 'react-i18next'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<React.Suspense fallback='loading...'>
<Router>
<I18nextProvider i18n={i18n}>
<App />
</ I18nextProvider>
</Router>
</React.Suspense>
</React.StrictMode>,
)
我的 Translation.json 文件位于 public/locales/en/translation.json
其中包含翻译如下:
{
"heroTitle": "Welcome to My Website",
"heroSubTitle": "Find everything you need"
}
以下是我正在处理的组件中的代码:
function Hero() {
const { t } = useTranslation()
return (
<div>
<h1>{t("heroTitle")}</h1>
<h3>{t("heroSubTitle")}</h3>
</div>
)
}
export default Hero
当我运行应用程序时,会出现以下文本:
heroTitle
heroSubTitle
如何让数值显示出来?
每当
i18n
无法识别给定的 key
(例如,heroTitle
)时,作为最后手段,它会显示 key
- 这是个好消息,因为它表明 react-i18next
模块正在运行正确地
就您而言,唯一的问题是您设置了
loadPath
不正确,正如@Malcolm 提到的。让我们仔细检查一下您的loadPath
:
loadPath: '/locales/{{lng}}/{{ns}}.json',
以
en
为例,loadPath
设置为绝对路径,这意味着它将在http://localhost:8080/locales/en/translation.json
(假设端口为8080
)加载翻译文件,而不是http://localhost:8080/public/locales/en/translation.json
。
您可能希望将上述设置更改为两个路径中的任意一个:
loadPath: '/public/locales/{{lng}}/{{ns}}.json',
loadPath: '../public/locales/{{lng}}/{{ns}}.json',
以上两个解决方案应该有帮助。