上次写完react-intl的国际化入门之后,发现react-intl有一个问题,那就是不支持hooks,而react-i18next是支持react的hooks写法的。i18next也是一个很完备的国际化方案,为 React、AngularJS、Vue.js 等前端框架创建了集成。
1.安装
npm install --save react-i18next
2.配置多语言映射关系
推荐使用json格式,可以在项目中新建文件夹locale统一管理,例如:
在index中,导入各语言包,并导入i18n执行初始化
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import enUS from './en_US.json';
import zhCN from './zh_CN.json';
const resources = {
'en-US': {
translation: enUS,
},
'zh-CN': {
translation: zhCN,
},
};
i18n.use(initReactI18next).init({
resources,
lng: 'zh-CN',
interpolation: {
escapeValue: false,
},
});
export default i18n;
3.导入文件
import React, { Component } from "react";
import ReactDOM from "react-dom";
import App from './App';
import './locale/index'; // 在这里导入
ReactDOM.render(
<App />,
document.getElementById("root")
);
4.使用
react-i18next提供了多种使用方式
1.hooks
在函数式组件中,使用hook是最为方便的,用t()包裹需要国际化的内容即可
import * as React from 'react';
import { useTranslation } from 'react-i18next';
const Hello: React.FC = () => {
const { t, i18n } = useTranslation();
return (
<div className="hello">
<h1>{t('hello')}</h1>
</div>
);
};
export default Hello;
2.高阶组件HOC
高阶组件也是常用的方法之一,用withTranslation处理组件,通过props传入t函数和i18n实例
import * as React from 'react';
import { withTranslation, WithTranslation } from 'react-i18next';
const Hello: React.FC<WithTranslation> = ({ t, i18n }) => {
return (
<div className="hello">
<h1>{t('hello')}</h1>
</div>
);
};
export default withTranslation()(Hello);
3.Translation组件
Translation可以让包裹其中的部分获取到t函数和i18n实例
import * as React from 'react';
import { Translation } from 'react-i18next';
const Hello: React.FC = () => {
return (
<div className="hello">
<Translation>
{
(t, { i18n }) => <h1>{t('hello')}</h1>
}
</Translation>
</div>
);
};
export default Hello;
4.Trans组件
import * as React from 'react';
import { Trans } from 'react-i18next';
const Hello: React.FC = () => {
return (
<div className="hello">
<Trans> hello </Trans>
</div>
);
};
export default Hello;