最近一个需求,就是将原有项目支持中英文切换。项目是由create-react-app搭建的,无法使用umi自带的国际化,便使用react-i18next
、 i18next
来实现。
react国际化
安装依赖react-i18next、i18next
# npm
$ npm install react-i18next i18next --save
在src下新建目录i18n;i18n目录下新建index.ts文件、zh.json、en.json文件
index.ts
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import en from './en.json';
import zh from './zh.json';
// 获取本地存储预览、浏览器默认选中语言
const lang = localStorage.getItem('local') || (['en' , 'en-US', 'en-us'].includes(navigator.language) ? 'en' : 'zh');
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
// the translations
// (tip move them in a JSON file and import them,
// or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui)
resources: {
en: {
translation: en
},
zh: {
translation: zh
}
},
lng: lang, // if you're using a language detector, do not define the lng option
// fallbackLng: "en",
interpolation: {
escapeValue: false // react already safes from xss => https://www.i18next.com/translation-function/interpolation#unescape
}
});
export default i18n;
en.json
{
"hello": "hello,I'm {{name}}",
"Home": {
"mainTitle": "mainTitle",
"subTitle" : "subTitle"
}
}
zh.json
{
"hello": "你好,我是{{name}}",
"Home": {
"mainTitle": "主标题",
"subTitle" : "子标题"
}
}
切换语言
import i18n from "i18next";
// 切换中英语言
const handleChangLang = (currentLang) => {
i18n.changeLanguage(currentLang);
localStorage.setItem('local', currentLang);
}
使用
import { useTranslation } from "react-i18next";
import i18next from "i18next";
export default function AboutLang(props) {
const { t } = useTranslation();
return (
<div style={{ height: 600 }}>
{/* 带动态字段 */}
<p> {t("hello", { name: 'Yan' })}</p>
{/* 纯文本文案 */}
<h1>{t("Home.mainTitle")}</h1>
{/* 在非组件中可以使用 */}
<h3>
{i18next.t("hello", { name: 'Kiimi' })}
</h3>
</div>
)
}
更详情内容查看官网
i18next官网:i18next官网
react-i18next官网:react-i18next官网