平时中会遇到需求,就是切换语言,语种等。其实总的来说都是用i18n来实现的
首先在项目中安装i18n插件,然后将插件引入到项目,然后配置语言包(语言包需要你自己来进行配置,自己编写语言包,或者你能找到跟你项目适配的也可以),然后就用特定的方法来展示可以切换语言的字段
需要同时安装 i18next 和 react-i18next 依赖:
npm install react-i18next i18next --save
在src下新建i18n文件夹,以存放国际化相关配置i18n中分别新建三个文件
config.ts:对 i18n 进行初始化操作及插件配置
en.json:英文语言配置文件
zh.json:中文语言配置文件

- import i18n from 'i18next';
- import { initReactI18next } from 'react-i18next';
- import translation_en from './en.json';
- import translation_zh from './zh.json';
-
- const resources = {
- en: {
- translation: translation_en,
- },
- zh: {
- translation: translation_zh,
- },
- };
-
- i18n.use(initReactI18next).init({
- resources,
- // 默认语言 zh/en 中文/英文
- lng: 'zh',
- interpolation: {
- escapeValue: false,
- },
- });
-
- export default i18n;
- {
- "language":"语言",
- "switch":"选择",
- }
-
- {
- "language":"Language",
- "switch":"Switch",
- }
-
在 page 的index.tsx中引用i18n的配置文件 :import '../i18n/config';
- import Page1 from './page1';
- import Page2 from './page2';
- // 引用配置文件
- import '../i18n/config';
-
- export default function IndexPage() {
- return (
- <div>
- <Page1 />
- <Page2 />
- </div>
- );
- }
-
在 函数式组件 中使用useTranslation 的 hook 来处理国际化
- // Page1 函数式组件
- import React from 'react';
- // 引入 useTranslation
- import { useTranslation } from 'react-i18next';
-
- const Page1: React.FC = () => {
- const { t } = useTranslation();
- return (
- <div>
- <p>这是Page1</p>
- <p>{t('language')}</p>
- </div>
- );
- };
-
- export default Page1;
-
在 类组件 中使用withTranslation 高阶函数(HOC) 来完成语言配置的数据注入
- // Page2 类组件
- import React from 'react';
- // 引入HOC高阶函数 withTranslation 和 i18n 的ts类型定义 WithTranslation
- import { withTranslation, WithTranslation } from 'react-i18next';
-
- class ClassComponent extends React.Component<WithTranslation> {
- render() {
- const { t } = this.props;
- return (
- <div>
- <p>{t('language')}</p>
- </div>
- );
- }
- }
- // withTranslation 完成语言配置数据注入
- export const Page2 = withTranslation()(ClassComponent);
-
使用changeLanguage() config 中配置 切换语言
- // 函数式组件
- import React from 'react';
- import { useTranslation, Trans } from 'react-i18next';
-
- const Page1: React.FC = () => {
- const { t, i18n } = useTranslation();
- return (
- <div>
- <button onClick={() => i18n.changeLanguage(i18n.language == 'en' ? 'zh' : 'en')}>
- {i18n.language == 'en' ? 'zh' : 'en'}
- </button>
- <p>{t('language')}</p>
- </div>
- );
- };
-
- export default Page1;
- // 类式组件
- import i18n from 'i18next';
-
- const changeLanguage= (val) => {
- i18n.changeLanguage(val); // 传入 'en' / 'zh'
- };