React i18n多语言实现

目前比较流行的三种方式
react-i18next
react-intl
react-intl-universa

what is react-i18next?
react-i18next is a powerful internationalization framework for React / React Native which is based on i18next(https://www.i18next.com).


https://react.i18next.com/

1.Install
$ npm install react-i18next i18next --save

2.Configure i18next

3.Translate your content

3.1使用 useTranslation hook

import React from 'react';
// the hook
import { useTranslation } from 'react-i18next';
function MyComponent () {
const { t, i18n } = useTranslation();
return <h1>{t('hello')}</h1> //你好!
}

  

3.withTranslation 使用高階組件 (HOC)

import React from 'react';
// the hoc
import { withTranslation } from 'react-i18next';
function MyComponent ({ t }) {
return <h1>{t('hello')}</h1>
}
export default withTranslation()(MyComponent);

  

3.3使用 render prop

import React from 'react';
// the render prop
import { Translation } from 'react-i18next';
export default function MyComponent () {
return (
<Translation>
{
t => <h1>{t('hello')}</h1>
}
</Translation>
)
}

  

3.4使用 Trans 元件

import React from 'react';
import { Trans } from 'react-i18next';
export default function MyComponent () {
return (
<Trans i18nKey="link">
一起來
<a>這裡</a>
學習 React 吧
</Trans>
)
}
传参数的两种方式
<Trans i18nKey="userMessagesUnread" values={{ name, count }}></Trans>


<Trans i18nKey="userMessagesUnread_plural">{{ name, age, from }}</Trans>

  

4.切換語言

const { t, i18n } = useTranslation();
const changeLanguage(lng: string)
{
    i18n.changeLanguage(lng);
}

<button onClick={() => this.changeLanguage('zh')}>Chinese</button>

<button onClick={() => this.changeLanguage('en')}>Engligh</button>

  

人生旅途,边走边看...
原文地址:https://www.cnblogs.com/dming4/p/15470592.html