React 中使用 react-i18next 国际化

360 阅读2分钟

官方地址:react-i18next | i18next


1.安装react-i18next、i18next

npm install react-i18next i18next --save
  1. 创建目录locales,分别放en.json和zh.json,如下:

image.png
3. 在src下新建文件i18n.js

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from './locales/en.json'
import zh from './locales/zh.json'
import LanguageDetector from 'i18next-browser-languagedetector'

const resources = {
  "en": {
		translation: en
	},
	"zh": {
		translation: zh
	}
}
const currentLocale = localStorage.getItem('lan', name) || 'zh';
console.log(currentLocale)

i18n
	// 将 i18n 实例传递给 react-i18next
	.use(LanguageDetector)
	.use(initReactI18next)
	// 初始化 i18next
	// 所有配置选项: https://www.i18next.com/overview/configuration-options
	.init({
		resources,
		fallbackLng: "zh", // 默认当前的语言环境
		lng: "zh",
		debug: true,
		interpolation: {
			escapeValue: false, // not needed for react as it escapes by default
		}
	});

export default i18n;
  1. 在程序入口(main.jsx)引入i18n
import './i18n'
  1. 语言环境的切换
import { useTranslation } from "react-i18next";
const { i18n } = useTranslation();

const changeLan = (name) => {
    setLocale(name)
    i18n.changeLanguage(name); 
  }
<div className='logo'>
    <span className='lanTextZh' style={locale === 'zh' ? {'color': '#1677FF'} : {'color': '#fff'}} onClick={() => changeLan('zh')}>中文</span>
    <span className='lanTextEn' style={locale === 'en' ? {'color': '#1677FF'} : {'color': '#fff'}} onClick={() => changeLan('en')}>EN</span>
    <span style={{'marginLeft': '40px' }}>hello,</span><span style={{'paddingLeft': '10px'}}>{user_name}</span>
    <span className='logOutTag' onClick={handleLogout}>Log Out</span>
</div>
  1. ant design组件中国际化语言的使用
    官方文档:antd design组件国际化

image.png

image.png

import zhCN from 'antd/locale/zh_CN';
import enUS from 'antd/locale/en_US';
import { ConfigProvider } from 'antd';

<ConfigProvider locale={locale === 'zh' ? zhCN : enUS}>
   <Outlet></Outlet>
 </ConfigProvider>
  1. 国际化语言的使用
import { useTranslation } from "react-i18next";
const { t } = useTranslation();  // 国际化语言
<div>
  <Button type="primary" icon={<PlusOutlined />} size={size} onClick={importResouce}>
    {t('wallpaper.importResource')}
  </Button>
  <Button size={size} className="ml10" onClick={importRecord}>
    {t('wallpaper.importRecord')}
  </Button>
</div>
  1. 当国际化含有变量字符串的时候
    zh.json文件
{
    "common": {
        "totalItems": "一共{{total}}条数据",
    }
}

en.json文件

{
    "common": {
        "totalItems": "Total {{total}} items",
    }
}

jsx组件中的使用方法:

import { useTranslation } from "react-i18next";
const { t } = useTranslation(); 
const showLogTotal = (total) => t('common.totalItems', {total: total})
  1. i18next-browser-languagedetector 会自动尝试检测浏览器的默认语言,我们可以把用户上次手动选择的语言存储到 localStorage 中,下次访问页面时使用上次存储的语言作为首选语言。