react-i18next国际化步骤
安装react-i18next和 i18next依赖
npm install react-i18next i18next
或
yarn add react-i18next i18next
在src下新建i18n文件夹,以存放国际化相关配置,可根据需要添加相应的语言文件
2.1 新建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 语言文件示例
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';
3.1 类(class)组件中使用
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 函数(function)组件或Hook中使用
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 切换语言功能
renderI18n = item => { const { i18n } = this.props; return ( <Button onClick={() => i18n.changeLanguage(i18n.language === 'en' ? 'zh' : 'en')}> {i18n.language === 'en' ? '切换成中文' : '切换成英文'} </Button> ); };
热门文章
- 「1月16日」最高速度20.6M/S,2025年SSR/Clash/V2ray/Shadowrocket每天更新免费订阅地址分享
- docker设置代理服务器,解决pull命令:Error response from daemon: Get https://registry-1.docker.io/v2…
- 狗领养协议有没有法律效应(领养狗协议书范本)
- 「1月19日」最高速度20.7M/S,2025年V2ray/Shadowrocket/SSR/Clash每天更新免费订阅地址分享
- 「2月23日」最高速度20.5M/S,2025年Clash/V2ray/Shadowrocket/SSR每天更新免费订阅地址分享
- 「2月2日」最高速度19.8M/S,2025年Shadowrocket/V2ray/Clash/SSR每天更新免费订阅地址分享
- es6操作数组方法
- 重庆宠物领养中心电话号码是多少啊(重庆最大免费宠物领养平台)
- 附近哪里有领养狗的地方呀(附近哪里可以领养狗狗)
- Linux 下清空或删除大文件/大量文件的几种方法