一起探讨学习
每天给大家提供技术干货
博主技术笔记 https://notes.xiyankt.com
博主开源微服架构前后端分离技术博客项目源码地址,欢迎各位star https://gitee.com/bright-boy/xiyan-blog
1.安装
npm install i18next react-i18next --save
2.在src文件下新建配置文件 i18n.js
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import Cookie from "js-cookie";
// not like to use this?
// have a look at the Quick start guide
// for passing in lng and translations on init
i18n
// load translation using xhr -> see /public/locales
// learn more: https://github.com/i18next/i18next-xhr-backend
// .use(Backend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
// .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({
resources: {
EN: {
translations: require("./locale/en.json"),
},
CN: {
translations: require("./locale/zh.json"),
},
},
// fallbackLng: 'zh-CN', // 使用LanguageDetector 取消注释
fallbackLng: Cookie.get("lang") === "EN" ? "EN" : "CN",
debug: true,
// have a common namespace used around the full app
ns: ["translations"],
defaultNS: "translations",
keySeparator: false, // we use content as keys
interpolation: {
escapeValue: false, // not needed for react!!
},
react: {
wait: true,
},
});
export default i18n;
3.静态资源下新建json语言包,有几种语言建几种包,文件名
例:
中文包 zh.json
{
"cn": "中文",
"en": "英语",
"welcome": "欢迎你:"
}
英文包 en.json
{
"cn": "CN",
"en": "EN",
"welcome": "Welcome:"
}
使用
将配置文件引入到indexjs入口文件
//引入i18n.js
import './i18n'
4.i18next的使用(简单方便,但是在当前页面不能及时刷新)
import i18next from "i18next";
// 这种写法,必须手动刷新,不能及时刷新
<div>{i18next.t("en")}</div>
react-i18next的使用(使用复杂,但在当前页面切换可以不刷新切换),使用时需要包裹当前组件
import { withTranslation } from "react-i18next";
<div style={{ margin: 10 }}>
<p>{this.props.t("en")}</p>
</div>
export default withTranslation("translations")(LongTxt);
hook写法使用
import { useTranslation } from "react-i18next";
const Dashboard = (props) => {
const { t } = useTranslation();
return <div>{t("welcome")}</div>
}
5.切换的时候设置语言
onClick = (key) => {
Cookie.set("lang", key.key)
//设置语言
i18next.changeLanguage(key.key.toUpperCase())
this.setState({locale: i18next.t(key.key.toUpperCase())})
};