react使用国际化

最近一个需求,就是将原有项目支持中英文切换。项目是由create-react-app搭建的,无法使用umi自带的国际化,便使用react-i18next i18next来实现。

react国际化

安装依赖react-i18next、i18next

# npm
$ npm install react-i18next i18next --save

在src下新建目录i18n;i18n目录下新建index.ts文件、zh.json、en.json文件

index.ts

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import en from './en.json';
import zh from './zh.json';

// 获取本地存储预览、浏览器默认选中语言
const lang = localStorage.getItem('local') || (['en' , 'en-US', 'en-us'].includes(navigator.language)  ? 'en' : 'zh');

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    // the translations
    // (tip move them in a JSON file and import them,
    // or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui)
    resources: {
      en: {
        translation: en
      },
      zh: {
        translation: zh
      }
    },
    lng: lang, // if you're using a language detector, do not define the lng option
    // fallbackLng: "en",
    interpolation: {
      escapeValue: false // react already safes from xss => https://www.i18next.com/translation-function/interpolation#unescape
    }
  });

export default i18n;

en.json

{
  "hello": "hello,I'm {{name}}",
  "Home": {
    "mainTitle": "mainTitle",
    "subTitle" : "subTitle"
  }
}

zh.json

{
  "hello": "你好,我是{{name}}",
  "Home": {
    "mainTitle": "主标题",
    "subTitle" : "子标题"
  }
}

切换语言

import i18n from "i18next";

// 切换中英语言
const handleChangLang = (currentLang) => {
  i18n.changeLanguage(currentLang);
  localStorage.setItem('local', currentLang);
}

使用

import { useTranslation } from "react-i18next";
import i18next from "i18next";
export default function AboutLang(props) {

  const { t } = useTranslation();
  return (
    <div style={{ height: 600 }}>
      {/* 带动态字段 */}
      <p> {t("hello", { name: 'Yan' })}</p>
      {/* 纯文本文案 */}
      <h1>{t("Home.mainTitle")}</h1>
      {/* 在非组件中可以使用 */}
      <h3>
        {i18next.t("hello", { name: 'Kiimi' })}
      </h3>
    </div>
  )
}

更详情内容查看官网

i18next官网:i18next官网

react-i18next官网:react-i18next官网

umi3使用国际化,可以查看文章

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值