React 场景下基于 react-i18next 进行处理,api一致,如需更多功能可查询官方网站
npm install @volcengine/i18n
新建 i18n.js
import reactI18n from '@volcengine/i18n' reactI18n.init({ lng: 'zh', backend: { namespace: 3174, operatorId: 210041130, apiKey: '704dbe7057f510ec8e4aedf71dc34d4f', projectId: 4168, }, react: { useSuspense: true, // 默认为true,false关闭Suspense } }) export default reactI18n
入口index.js
默认开启 Suspense,如不需要支持关闭
import React, { Suspense } from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './i18n'; ReactDOM.render( <Suspense fallback="Loading..."> <App /> </Suspense>, document.getElementById('root') );
类组件
import { withTranslation } from '@volcengine/i18n'; class Page extends Component { render() { const { t, i18n } = this.props; ... } } export default withTranslation()(Page);
函数组件
import { useTranslation } from '@volcengine/i18n'; function Page() { const { t, i18n } = useTranslation(); ... } export default Page
切换语种
const { t, i18n } = useTranslation(); i18n.changeLanguage('en')
文案替换-正常
const { t } = useTranslation(); // { zh: { normal: '正常' }, en: { normal: 'normal' } } t('normal') // zh: 正常 en: normal
文案替换-带插值
特别提示:国际化翻译平台插值默认都以单花括号 {}
const { t } = useTranslation(); // { zh: { placeholder: '我是{name}' }, en: { placeholder: 'i am {name}' } } t('placeholder', { name: 'starling' }) // zh: 我是starling en: i am staring
文案替换-富文本且带插值-1
import { Trans } from '@volcengine/i18n'; /** * { * zh: { rich_text: '你好 <1>{name}</1>, 你有 {number} 条未读信息. <5>去查看</5>.' }, * en: { rich_text: 'Hello <1>{name}</1>, you have {number} unread message. <5>Go to message</5>.' } * } */ const name = 'starling', number = 10 <Trans i18nKey="rich_text"> Hello <strong>{{name}}</strong>, you have {{number}} unread message. <a to="/msgs">Go to messages</a>. </Trans>
文案替换-富文本且带插值-2
import { Trans } from '@volcengine/i18n'; /** * { * zh: { rich_text: '你好 <1>{name}</1>, 你有 {number} 条未读信息. <5>去查看</5>.' }, * en: { rich_text: 'Hello <1>{name}</1>, you have {number} unread message. <5>Go to message</5>.' } * } */ const name = 'starling', number = 10 <Trans i18nKey="rich_text" values={{ name, number }} components={[ 'Hello ', <strong>{{ name }}</strong>, ', you have ', '{number}', ' unread message. ', <a to="/msgs">Go to messages</a>, '.' ]} />
文案替换-icu格式
需要提前安装icu-i18next
在本实例中是通过 num 插值去判断是否为复数
const { t } = useTranslation(); // { zh: { icu: '{num, plural, other {人}}' }, en: { icu: '{num, plural, one {person} other {persons}}' } } t('icu', { num: 1 }) // zh: 人 en: person
该函数为高阶组件,会往class组件props注入 t 和 i18n
该函数为hooks,返回 t 和 i18n
react中国际化富文本组件,使用
| 属性 | 类型 | 说明 |
|---|---|---|
| i18nKey | string | 国际化翻译平台对应key |
| values | object | 存在插值时的对象 |
| components | array | 基于标签索引来插入的组件 |
| count | number | 采用复数时表示当前采用哪种复数的值 |
更改当前应用语种
const { t, i18n } = useTranslation(); i18n.changeLanguage('en')
运行时对文案进行替换