目前比較流行的三種方式
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>