安装react-i18next和 i18next依赖
npm install react-i18next i18next
或
yarn add react-i18next i18next
在src下新建i18n文件夹,以存放国际化相关配置,可根据需要添加相应的语言文件
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;
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": "这是个中文段落" } }
首先在index.jsx中引入国际化配置文件
import './i18n/config';
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);
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;
renderI18n = item => { const { i18n } = this.props; return ( <Button onClick={() => i18n.changeLanguage(i18n.language === 'en' ? 'zh' : 'en')}> {i18n.language === 'en' ? '切换成中文' : '切换成英文'} </Button> ); };