详细介绍 React 中 i18n 的完整使用流程:

接下来按照步骤,让我们来完成!

javascript 复制代码
// 1. 首先安装必要的依赖
// npm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector

// 2. 创建 i18n 配置文件 (src/i18n/index.js)
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'  // react-i18next 的初始化插件
import Backend from 'i18next-http-backend'  // 用于动态加载翻译文件
import LanguageDetector from 'i18next-browser-languagedetector'  // 用于检测浏览器语言

// i18n 初始化配置
i18n
  // 使用 i18next-http-backend 插件
  // 这个插件允许我们从服务器动态加载翻译文件
  .use(Backend)
  
  // 使用 i18next-browser-languagedetector 插件
  // 这个插件会自动检测用户的语言环境
  .use(LanguageDetector)
  
  // 将 i18next 集成到 react 中
  .use(initReactI18next)
  
  // 初始化 i18next
  .init({
    // 默认语言
    fallbackLng: 'en',
    
    // 是否在开发环境打印调试信息
    debug: process.env.NODE_ENV === 'development',
    
    // 翻译文件的路径配置
    backend: {
      loadPath: '/locales/{{lng}}/{{ns}}.json',  // 翻译文件路径模板
    },
    
    // 翻译文件的命名空间
    ns: ['translation'],
    defaultNS: 'translation',
    
    // 插值配置
    interpolation: {
      // 是否转义 HTML 标签
      escapeValue: false,
    },
    
    // 检测语言的配置
    detection: {
      // 存储语言选择的 key
      lookupLocalStorage: 'i18nextLng',
      // 缓存用户语言选择
      caches: ['localStorage'],
    },
  })

export default i18n

// 3. 创建翻译文件
// public/locales/en/translation.json
{
  "welcome": "Welcome",
  "hello": "Hello, {{name}}!",
  "nav": {
    "home": "Home",
    "about": "About",
    "contact": "Contact"
  },
  "form": {
    "username": "Username",
    "password": "Password",
    "submit": "Submit"
  }
}

// public/locales/zh/translation.json
{
  "welcome": "欢迎",
  "hello": "你好,{{name}}!",
  "nav": {
    "home": "首页",
    "about": "关于",
    "contact": "联系"
  },
  "form": {
    "username": "用户名",
    "password": "密码",
    "submit": "提交"
  }
}

// 4. 在 App.js 中配置 i18n
import React from 'react'
import { I18nextProvider } from 'react-i18next'
import i18n from './i18n'

function App() {
  return (
    // 使用 I18nextProvider 包裹应用
    <I18nextProvider i18n={i18n}>
      <YourApp />
    </I18nextProvider>
  )
}

// 5. 在组件中使用 i18n
import React from 'react'
import { useTranslation } from 'react-i18next'  // 引入 useTranslation hook

function MyComponent() {
  // 解构 t 函数和 i18n 实例
  const { t, i18n } = useTranslation()
  
  // 切换语言的函数
  const changeLanguage = (lng) => {
    i18n.changeLanguage(lng)
  }
  
  return (
    <div>
      {/* 基本翻译 */}
      <h1>{t('welcome')}</h1>
      
      {/* 带变量的翻译 */}
      <p>{t('hello', { name: 'John' })}</p>
      
      {/* 嵌套的翻译 */}
      <nav>
        <a href="/">{t('nav.home')}</a>
        <a href="/about">{t('nav.about')}</a>
        <a href="/contact">{t('nav.contact')}</a>
      </nav>
      
      {/* 语言切换按钮 */}
      <div>
        <button onClick={() => changeLanguage('en')}>English</button>
        <button onClick={() => changeLanguage('zh')}>中文</button>
      </div>
      
      {/* 表单示例 */}
      <form>
        <div>
          <label>{t('form.username')}</label>
          <input type="text" />
        </div>
        <div>
          <label>{t('form.password')}</label>
          <input type="password" />
        </div>
        <button type="submit">{t('form.submit')}</button>
      </form>
    </div>
  )
}

// 6. 高级用法示例

// 6.1 使用 Trans 组件处理复杂的 HTML
import { Trans } from 'react-i18next'

function ComplexComponent() {
  return (
    <Trans i18nKey="description">
      This is a <strong>bold</strong> text with <a href="/">link</a>.
    </Trans>
  )
}

// 6.2 使用 HOC 包装组件
import { withTranslation } from 'react-i18next'

class MyClassComponent extends React.Component {
  render() {
    const { t } = this.props
    return <h1>{t('welcome')}</h1>
  }
}

export default withTranslation()(MyClassComponent)

// 6.3 懒加载翻译文件
const loadLocales = (language) => {
  return import(`./locales/${language}.json`).then(
    (module) => module.default
  )
}

// 6.4 处理复数
// translation.json
{
  "items": {
    "zero": "没有项目",
    "one": "1个项目",
    "other": "{{count}}个项目"
  }
}

// 使用
function PluralExample() {
  const { t } = useTranslation()
  return <p>{t('items', { count: 2 })}</p>
}
相关推荐
子兮曰2 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰2 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万2 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝2 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋2 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁2 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
汉堡大王95272 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大2 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师2 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端
沙蒿同学2 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端