React 使用 i18next 实现国际语言切换翻译

引入 i18next 依赖

引入 i18next 和 react-i18next

bash 复制代码
npm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector

总结

依赖 作用
i18next 核心国际化库,提供翻译功能和资源管理。
i18next-http-backend 动态加载语言资源文件,避免将所有语言包打包到代码中,支持按需加载。
react-i18next i18next 与 React 集成,提供 React 特有的功能(如 Hooks 和 Context)。
i18next-browser-languagedetector 自动检测用户的浏览器语言偏好,并设置为默认语言,提升用户体验。

配置 i18next

js 复制代码
public/ 
└── locales/ 
    ├── en.json
    ├── index.ts
    └── zh.json

基础配置

核心文件 index.ts

js 复制代码
import i18next from 'i18next';
import Backend from 'i18next-http-backend';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

import enUsTrans from './en.json';
import zhCnTrans from './zh.json';

// 可动态传入翻译类型及其对应文件
const resources = {
    'en-US': {
        translation: enUsTrans,
    },
    'zh-CN': {
        translation: zhCnTrans,
    },
};

i18next
    .use(Backend)
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
        resources,
        fallbackLng: 'zh-CN', // 默认语言
        backend: {
            loadPath: '/locales/{{lng}}/{{ns}}.json', // 你的翻译文件所在的路径
        },
        // 检测到的语言可以在这里进行重写
        detection: {
            order: ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator'],
            caches: ['cookie'], // 缓存检测到的语言
        },
        // react i18next special options (optional)
        // override if needed - full list can be found in the documentation
        react: {
            useSuspense: false, // Set to true if you're using React Suspense
        },
    });

export default i18next;

语言文件 .json

英文

json 复制代码
{
    "welcome": "Welcome",
    "description": "This is a simple internationalization example.",
    "greeting": "hello, {{name}}"
}

中文

json 复制代码
{
    "welcome": "欢迎",
    "description": "这是一个简单的国际化示例。",
    "greeting": "你好, {{name}}"
}

程序文件 App.jsx

当前文件供参考,可根据实际情况进行调整

jsx 复制代码
import React, {useState} from 'react';
import { useTranslation } from 'react-i18next';

const App = () => {
    const { t, i18n } = useTranslation();
    const [currentLocale, setCurrentLocale] = useState('zh-CN');

    // 切换语言
    const changeLocale = (locale) => {
        setCurrentLocale(locale); 
        localStorage.setItem('language', locale); // 保存至 localStorage 确保刷新页面不失效
        i18n.changeLanguage(locale); // 切换匹配语言
    };

    return (
        <div>
            {/* 简单翻译 */}
            <h1>{t('welcome')}</h1>
            <p>{t('greeting', { name: 'Alice' })}</p>
            
            <button onClick={() => changeLocale('en-US')}>English</button>
            <button onClick={() => changeLocale('zh-CN')}>中文</button>
        </div>
    );
};

export default App;
相关推荐
布鲁飞丝27 分钟前
从零实现富文本编辑器#-浏览器选区与编辑器选区模型同步
java·前端·编辑器
写不来代码的草莓熊36 分钟前
Cesium 地图交互绘制圆形、多边形
前端·javascript·地图
weixin_427771611 小时前
前端版本检测
前端
禅思院1 小时前
流式 Markdown 渲染完全指南【引子】
前端·架构·前端框架
JackSparrow4141 小时前
前端安全之JS混淆+请求加密+请求签名以提升爬虫难度
前端·javascript·后端·爬虫·python·安全
IMPYLH2 小时前
HTML 的 <em> 元素
java·前端·html
看昭奚恤哭2 小时前
基于 RuoYi-Vue-Pro 定制了一个后台管理系统 magic-admin , 开源出来!
前端·vue.js·开源
名为沙丁鱼的猫7294 小时前
【审计日志组件实践复盘】前端工程化 + 后端DDD架构(AOP切面拦截日志) + MBG
前端·架构
xqqxqxxq4 小时前
AI智能旅游规划系统 - 前端技术笔记
前端·笔记·旅游
陈随易10 小时前
bm2,MoonBit实现的pm2替代品
前端·后端·程序员