文档地址
https://react.i18next.com/guides/quick-start
npm install react-i18next i18next --save
1、建立文件夹
src/i18n
src/i18n/configs.ts
src/i18n/en.json
src/i18n/zh.json
2、具体代码
src/i18n/configs.ts
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
// the translations
// (tip move them in a JSON file and import them,
// or even better, manage them separated from your code: https://react.i18next.com/guides/multiple-translation-files)
const resources = {
en: {
translation: {
"Welcome to React": "Welcome to React and react-i18next"
}
},
fr: {
translation: {
"Welcome to React": "Bienvenue à React et react-i18next"
}
}
};
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: "en", // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources
// you can use the i18n.changeLanguage function to change the language manually: https://www.i18next.com/overview/api#changelanguage
// if you're using a language detector, do not define the lng option
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;
src/i18n/en.json
src/i18n/zh.json
{
"xxx1": {
"key": "value",
},
"xxx2": {
"key": "value",
},
}
3、在入口文件main.js引入
src/main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './i18n/configs' // 直接引入就好
import {Provider} from 'react-redux';
import mixedstore from './redux/store/store'
import {PersistGate} from 'redux-persist/integration/react'
ReactDOM.render(
<React.StrictMode>
<Provider store={mixedstore.store}>
<PersistGate persistor={mixedstore.persistor}>
<App />
</PersistGate>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
4、通过i18n的changeLanguage方法改变当前语言
i18n.changeLanguage(action.payload)
5、语言显示
import React from 'react';
import {Typography} from 'antd'
import {Link} from 'react-router-dom'
import {useTranslation} from 'react-i18next'
export const Index = props =>{
const {t}=useTranslation();
return(
<div>
<Typography.Text type="danger">¥ {price} {t("xxx1.key")}</Typography.Text>
</div>
)
}
export default Production