react-i18next学习(国际化)
简介
项目国际化,是要求项目内的菜单及部分显示组件的语言可以国际化(支持语言配置)
react-i18next是基于i18next的一款强大的国际化框架,可以应用在react和react-native项目中。
使用过程
安装
需要配合i18next使用
npm install react-i18next i18next
配置
在src
下新建i18n
文件夹,以存放国际化相关配置
i18n
文件夹中新建3个文件:
config.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
//配置中文的配置文件
import translation_zh from './zh.json';
//配置英文的配置文件
import translation_en from './en.json';
const resources = {
en: {
translation: translation_en,
},
zh: {
translation: translation_zh,
},
};
i18n.use(initReactI18next).init({
resources,
lng: 'zh',
interpolation: {
escapeValue: false,
},
});
export default i18n;
zh.json
{
"header": {
"register": "注册",
"signin": "登录",
"home": "首页"
},
"footer": {
"detail": "版权所有 @ React"
},
"home": {
"hot_recommended": "爆款推荐",
"new_arrival": "新品上市",
"joint_venture": "合作企业"
},
"content": {
"description": "这是个中文段落"
}
}
en.json
{
"header": {
"register": "Register",
"signin": "Sign In",
"home": "Home"
},
"footer": {
"detail": "All rights reserved @ React"
},
"home": {
"hot_recommended": "Hot Recommended",
"new_arrival": "New arrival",
"joint_venture": "Joint Venture"
},
"content": {
"description": "this is a chinese graph"
}
}
使用
- 在index.jsx中引入国际化配置文件
//引用国际化配置文件
import './i18n/config';
这个配置需要在index.jsx中引入,否则会变异失败。
2. 在组件中使用
在函数组件中使用
import {useTranslation, Trans} from 'react-i18next';
function App() {
const {t, i18n} = useTranslation();
return (
<>
<div>
<span>{t('content.description')}</span>
</div>
<hr/>
<div>
<h1>{t('header.home')}</h1>
<li>{t('home.hot_recommended')}</li>
{/* 还有一种方式 */}
<li><Trans>home.new_arrival</Trans></li>
</div>
</>
);
}
export default App;
在类组件中使用
import React from 'react';
import {useTranslation, WithTranslation, withTranslation} from 'react-i18next';
class HomeComponent extends React.Component<WithTranslation> {
render() {
const {t} = this.props;
return
<>
<h1>{t('header.home')}</h1>
<ul>
<li>{t('home.hot_recommended')}</li>
<li>{t('home.new_arrival')}</li>
<li>{t('home.joint_venture')}</li>
</ul>
</>
}
}
export cost Home = withTranslation()(HomeComponent);
语言切换
在页面上放置语言语言切换触发方式
import {useTranslation} from 'react-i18next';
const ChangeLanguage = () => {
const {i18n} = useTranslation();
return (
<button onClick={() => i18n.changeLanguage(i18n.language==='en'?'zh':'en')}>{i18n.language==='en'?'zh':'en'}</button>
);
}
export default ChangeLanguage;
或者
import i18n from 'i18next';
const changeLanguage = (val) => {
i18n.changeLanguage(val); //val的值为zh或者en
}