React功能篇 – 使用react-i18next进行国际化

2023年2月17日13:26:48

一.安装依赖

安装react-i18next和 i18next依赖

npm install react-i18next i18next

yarn add react-i18next i18next

二.配置文件

在src下新建i18n文件夹,以存放国际化相关配置,可根据需要添加相应的语言文件
React功能篇 - 使用react-i18next进行国际化

2.1 新建config.js

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
//配置中文的配置文件
import translation_zh from './zh.json';
//配置英文的配置文件
import translation_en from './en.json';

const resources = {
  en: {
    translation: translation_en
  },
  zh: {
    translation: translation_zh
  }
};

i18n.use(initReactI18next).init({
  resources,
  lng: 'zh',
  interpolation: {
    escapeValue: false
  }
});

export default i18n;

2.2 语言文件示例

en.json

{
  "header": {
    "register": "Register",
    "signin": "Sign In",
    "home": "Home"
  },
  "footer": {
    "detail": "All rights reserved @ React"
  },
  "home": {
    "mainTip": "Im login page"
  },
  "content": {
    "description": "this is a chinese graph"
  }
}

zh.json

{
  "header": {
    "register": "注册",
    "signin": "登录",
    "home": "首页"
  },
  "footer": {
    "detail": "版权所有 @ React"
  },
  "home": {
    "mainTip": "我是登录页面"
  },
  "content": {
    "description": "这是个中文段落"
  }
}

三.详细使用

首先在index.jsx中引入国际化配置文件

import './i18n/config';

3.1 类(class)组件中使用

import React, { Component } from 'react';
import { withTranslation } from 'react-i18next';
class login extends Component {
  render() {
    const { t } = this.props;
    return (
      <div>
        <h1>{t('home.mainTip')}</h1>
      </div>
    );
  }
}
export default withTranslation()(login);

3.2 函数(function)组件或Hook中使用

import React from 'react';
import { useTranslation,Trans } from 'react-i18next';
function Example() {
  const { t, i18n } = useTranslation();
  return (
    <div>
    //第一种方式
      <p>{t('footer.detail')}</p>
    //第二种方式
      <li><Trans>home.new_arrival</Trans></li>
    </div>
  );
}
export default Example;

3.3 切换语言功能

renderI18n = item => {
    const { i18n } = this.props;
    return (
      <Button onClick={() => i18n.changeLanguage(i18n.language === 'en' ? 'zh' : 'en')}>
        {i18n.language === 'en' ? '切换成中文' : '切换成英文'}
      </Button>
    );
  };

  • 作者:情系半生e
  • 原文链接:https://blog.csdn.net/r657225738/article/details/124035454
    更新时间:2023年2月17日13:26:48 ,共 1711 字。