react-i18next internationalization steps
1. Installation dependencies
Install react-i18next and i18next dependencies
npm install react-i18next i18next
或
yarn add react-i18next i18next
2. Configuration file
Create a new i18n folder under src to store internationalization-related configurations, and add corresponding language files as needed
2.1 New 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;
2.2 Language file example
en.json
{
"header": {
"register": "Register",
"signin": "Sign In",
"home": "Home"
},
"footer": {
"detail": "All rights reserved @ React"
},
"home": {
"mainTip": "Im login page"
},
"content": {
"description": "this is a chinese graph"
}
}
zh.json
{
"header": {
"register": "注册",
"signin": "登录",
"home": "首页"
},
"footer": {
"detail": "版权所有 @ React"
},
"home": {
"mainTip": "我是登录页面"
},
"content": {
"description": "这是个中文段落"
}
}
Three. Detailed use
First introduce the internationalization configuration file in index.jsx
import './i18n/config';
3.1 Used in class components
import React, {
Component } from 'react';
import {
withTranslation } from 'react-i18next';
class login extends Component {
render() {
const {
t } = this.props;
return (
<div>
<h1>{
t('home.mainTip')}</h1>
</div>
);
}
}
export default withTranslation()(login);
3.2 Use in function components or Hooks
import React from 'react';
import {
useTranslation,Trans } from 'react-i18next';
function Example() {
const {
t, i18n } = useTranslation();
return (
<div>
//第一种方式
<p>{
t('footer.detail')}</p>
//第二种方式
<li><Trans>home.new_arrival</Trans></li>
</div>
);
}
export default Example;
3.3 Switch language function
renderI18n = item => {
const {
i18n } = this.props;
return (
<Button onClick={
() => i18n.changeLanguage(i18n.language === 'en' ? 'zh' : 'en')}>
{
i18n.language === 'en' ? '切换成中文' : '切换成英文'}
</Button>
);
};