在React中使用react-i18next实现前端国际化

在React中使用react-i18next实现前端国际化

hash070 737 2022-12-31

简介

react-i18next 是一个强大的基于i18next的React / React Native国际化框架。

使用react-i18next可以轻松满足前端工程的国际化需求,本文记录如何在React项目中使用react-i18next来实现前端国际化。

安装、配置与使用

安装依赖

# NPM 命令
npm i react-i18next i18next
# Yarn 命令
yarn add react-i18next i18next

配置

创建翻译文件

src/locales下创建一个cn.jsonen.json文件,分别表示项目的中文字符和英文字符。

例如:

cn.sjon

{
  "title": "你好世界"
}

en.json

{
  "title": "Hello World"
}

创建资源文件

在当前文件夹下创建一个资源文件

resourse.ts

import en from './en.json';
import cn from './cn.json';

// import locale json files from src/locales
export const resources = {
    "en": {
        "translation": en
    },
    "zh": {
        "translation": cn
    }
}

创建i18n初始化方法

再创建一个初始化i18n设定的代码

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import { resources } from './resources';

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

export default i18n;

在React入口中引入

import './locales/i18n'

在页面中使用

import './App.css'
import {useTranslation} from "react-i18next";//引入react-i18next的useTranslation钩子函数

function App() {
    //创建函数别名
    const {t} = useTranslation();

    return (
        <div className="App">
            <h1>{t('title')}</h1>
        </div>
    )
}

export default App

注:

此时我的项目src目录结构如下:

.../src$ tree
.
├── App.css
├── App.tsx
├── assets
│   └── react.svg
├── index.css
├── locales
│   ├── en-US.json
│   ├── i18n.ts
│   ├── resources.ts
│   └── zh-CN.json
├── main.tsx
└── vite-env.d.ts

2 directories, 10 files

检测并自动适配浏览器语言

完成多语言支持后,你会发现在浏览器开发工具=>Sensors=>Location=>Locale中更改语言后,没有像预期的那样自动调整输出语言。

这里我们需要使用另一个能检测浏览器的语言的依赖来解决这个问题。

安装i18next-browser-languagedetector

# NPM 安装
npm i i18next-browser-languagedetector
# Yarn 安装
yarn add i18next-browser-languagedetector

将该插件引入到i18n初始化方法中

新增导入LanguageDetector插件,然后将该插件引入到i18n中。

再把init()函数中的lng选项改为navigator.language,这个值来自于浏览器的Locales,表示浏览器当前正在使用的语言。

i18n.ts

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import { resources } from './resources';

i18n
    // 将 i18n 实例传递给 react-i18next
    .use(initReactI18next)
    // 引入languagedetector语言检测器
    .use(LanguageDetector)
    // 初始化 i18next
    // 所有配置选项: https://www.i18next.com/overview/configuration-options
    .init({
        resources,
        fallbackLng: "en-US",
        lng: navigator.language,
        debug: true,
        // interpolation: {
        //     escapeValue: false, // not needed for react as it escapes by default
        // }
    });

export default i18n;

手动更改语言

前端不仅应该可以自动识别并显示语言,也应该给用户手动选择语言的选项。

在代码中实现的方法:

// 在类式组件中
const { t, i18n } = this.props;
i18n.changeLanguage("en"); 		// 手动切换到英文

// 在函数式组件中使用
const { t, i18n } = useTranslation();
i18n.changeLanguage("zh"); 		// 手动切换到中文

最终效果:

中文:

image-20221231151738353

英文:

image-20221231151705575

参考文章:https://www.cnblogs.com/operate/p/16199940.html