安装
需要同时安装 i18next 和 react-i18next 依赖:
npm install react-i18next i18next --save
其它插件:
检测当前浏览器语言国际化组件:
npm install i18next-browser-languagedetector --save
配置
在src下新建i18n文件夹,以存放国际化相关配置
i18n中分别新建三个文件:
config.ts:对 i18n 进行初始化操作及插件配置 en.json:英文语言配置文件 zh.json:中文语言配置文件
config.ts
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import translation_en from './en.json'
import translation_zh from './zh.json'
const resources = {
en: {
translation: translation_en
},
zh: {
translation: translation_zh
}
}
i18n
// 通过i18next-browser-languagedetector检测浏览器语言
.use(LanguageDetector)
// 初始化 将i18n传递给react-i18next
.use(initReactI18next)
.init({
resources,
lng: 'zh',
interpolation: {
// escapeValue: false // react已经做了转义,不需要再转义
escapeValue: false
}
}).then()
export default i18n
en.json
{
"header": {
"location": "Choose Your Location",
"search_text": "Enter the content and press Enter to search"
},
"footer": {
"detail": "All rights reserved @ React"
}
}
zh.json
{
"header": {
"location": "选择你的位置",
"search_text": "输入内容然后按回车键进行搜索"
},
"footer": {
"detail": "保留所有权利 @ React"
}
}
App.tsx
只需引入config.ts即可
import './i18n/config'
使用
语言切换
import React from 'react'
import { useTranslation } from 'react-i18next'
const App: React.FC = () => {
const { t, i18n } = useTranslation()
const changeLanguage = (lng: string) => {
i18n.changeLanguage(lng)
}
return (
<div>
<h1>{t('header.location')}</h1>
<p>{t('header.search_text')}</p>
<button onClick={() => changeLanguage('en')}>English</button>
<button onClick={() => changeLanguage('zh')}>中文</button>
</div>
)
}