react-i18next
-
安装包:
npm install react-i18next i18next --save
-
添加语言包配置文件:
image.png-
en-US.json
{ "用户名": "username", "头像": "avatar", "语言": { "切换到中文": "change to Chinese", "切换到英文": "change to English" } }
-
zh-CN.json
{ "用户名": "用户名", "头像": "头像", "语言": { "切换到中文": "切换到中文", "切换到英文": "切换到英文" } }
-
i18n.js
import i18n from 'i18next' import { initReactI18next } from 'react-i18next' import enUS from './en_US.json' import zh from './zh_CN.json' const resources = { 'en-US': { translation: enUS, }, 'zh-CN': { translation: zh, }, } let localLang = localStorage.getItem('lang') if (!localLang) { const browserLanguage = navigator.language || navigator.userLanguage localLang = browserLanguage === 'zh-CN' ? 'zh-CN' : 'en-US' } i18n .use(initReactI18next) .init({ resources, lng: localLang, interpolation: { escapeValue: false, }, }) export default i18n
-
-
将
i18n.js
文件引入到入口文件中src/index.js
import './assets/locales/i18n'
-
在
src/App.js
文件中配置antd
语言包
import React from 'react'
import { ConfigProvider } from 'antd'
import { useTranslation } from 'react-i18next'
import zhCN from 'antd/locale/zh_CN'
import enUS from 'antd/locale/en_US'
const App = () => {
const { i18n } = useTranslation()
return (
<ConfigProvider locale={i18n.language === "zh-CN" ? zhCN : enUS}>
<div>
......
</div>
</ConfigProvider>
)
}
export default App
-
渲染组件
-
useTranslation (hook)
import React from 'react' import { useTranslation } from 'react-i18next' const RenderByHook = () => { const [t, i18n] = useTranslation() return <div>{t('语言.hook')}</div> } export default RenderByHook
-
withTranslation (HOC)
import React from 'react' import { withTranslation } from 'react-i18next' const RenderByHoc = ({ t, i18n }) => { return <div>{t('语言.hoc')}</div> } export default withTranslation()(RenderByHoc)
-
Translation (render prop)
import React from 'react' import { Translation } from 'react-i18next' const RenderByProps = () => { return ( <Translation> { (t, { i18n }) => <div>{t('语言.renderProps')}</div> } </Translation> ) } export default RenderByProps
-
-
切换语言
import React from 'react' import { Button } from 'antd' import { useTranslation } from 'react-i18next' export default () => { const [t, i18n] = useTranslation() const isZhCN = i18n.language === "zh-CN" const toggleI18n = () => { const locale = isZhCN ? "en-US" : "zh-CN" localStorage.setItem('lang', locale) i18n.changeLanguage(locale) } return ( <Button type="primary" onClick={toggleI18n}> {isZhCN ? t('语言.切换到英文') : t('语言.切换到中文')} </Button> ) }
react-intl
-
安装包:
npm i -S react react-intl
-
添加语言包配置文件:
- 与
react-i18next
不同的是,语言包文件类型为js,导出一个对象
- 与
-
渲染组件
- intl.formatMessage()
- <FormattedMessage id='welcome' />
-
切换语言
- 手动实现
网友评论