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

一.安装依赖

安装react-i18next和 i18next依赖

npm install react-i18next i18next

yarn add react-i18next i18next

二.配置文件

在src下新建i18n文件夹,以存放国际化相关配置,可根据需要添加相应的语言文件
在这里插入图片描述

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>
    );
  };
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

情系半生e

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值