1、安装
npm install i18next reacti18next -S
2、使用
(1)、准备语言包
{
"en":{
"common":{
"aticle":"aticle",
"files":"files",
"notebook":"notebook",
"comments":"comments",
"about":"about",
"zh_CN":"chinese",
"en_US":"english"
}
},
"zh":{
"common":{
"aticle":"文章",
"files":"归档",
"notebook":"知识小册",
"comments":"留言板",
"about":"关于",
"zh_CN":"中文",
"en_US":"英文"
}
}
}
(2)、在项目中使用
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import language from './localanuage.json'
export let languageKeys = [
'zh_CN','en_US'
]
// 初始化i18n
const initI18n = (locale:any) => {
const resources = {
zh_CN: {
translation: locale.zh,
},
en_US: {
translation: locale.en,
}
};
i18n.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: 'en_US',
debug: false,
// keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false, // react already safes from xss
},
});
};
initI18n(language) export default i18n;
(3)、在index.ts中引入
import './i18n'
(4)、切换语言
getI18n().changeLanguage('en_US')