You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中实现类似Vue.js mixin的全局翻译方法调用

React全局调用翻译函数实现方案

方案1:自定义Hook(最推荐,符合React开发规范)

适合所有使用函数组件的项目,无额外性能开销,使用灵活。

  • 第一步:将翻译函数封装为独立工具模块,新建src/utils/i18n.js,代码如下:
export function __(key, replace = null) {
    let translation, translationNotFound = true;

    try {
        translation = key.split('.').reduce((t, i) => t[i] || null, window._translations[window._locale].php);

        if (translation) {
            translationNotFound = false;
        }
    } catch (e) {
        translation = key;
    }

    if (translationNotFound) {
        translation = window._translations[window._locale]['json'][key]
            ? window._translations[window._locale]['json'][key]
            : key;
    }

    if (replace) {
        replace.forEach((value, key) => {
            translation = translation.replace(':' + key, value);
        });
    }

    return translation;
}

// 封装自定义Hook
export function useTranslation() {
  return { __ };
}
  • 第二步:任意函数组件中直接引入使用即可:
import { useTranslation } from '@/utils/i18n';

function DemoComponent() {
  const { __ } = useTranslation();
  // 基础用法
  const title = __('page.home.title');
  // 带参数用法
  const welcomeTip = __('page.home.welcome', { name: '张三' });
  return <div>{title}</div>
}

方案2:Context全局注入(适合需要动态切换语言的场景)

如果项目需要支持运行时切换语言,选择该方案可全局响应语言变更。

  • 第一步:新建src/contexts/TranslationContext.js:
import { createContext, useContext } from 'react';
import { __ } from '@/utils/i18n';

const TranslationContext = createContext({ __ });

export function TranslationProvider({ children }) {
  // 后续新增语言切换逻辑时,仅需修改该Provider内部逻辑即可
  const contextValue = { __ };
  return (
    <TranslationContext.Provider value={contextValue}>
      {children}
    </TranslationContext.Provider>
  )
}

export function useTranslation() {
  return useContext(TranslationContext);
}
  • 第二步:在项目入口根组件中引入Provider包裹全局内容,示例src/App.jsx:
import { TranslationProvider } from '@/contexts/TranslationContext';

function App() {
  return (
    <TranslationProvider>
      {/* 原有路由、全局组件等内容 */}
    </TranslationProvider>
  );
}

export default App;
  • 第三步:组件使用方式和自定义Hook方案完全一致,直接引入useTranslation调用即可。

方案3:挂载原型(最快实现,仅推荐小型项目使用)

如果想要实现类似Vue全局挂载的效果,不需要在每个组件引入,可直接挂载到React原型:

  • 在入口文件src/main.jsx中添加如下代码:
import React from 'react';
import { __ } from '@/utils/i18n';

React.prototype.__ = __;
  • 类组件中可直接调用:
class DemoComponent extends React.Component {
  render() {
    return <div>{this.__('page.home.title')}</div>
  }
}

注意:该方案不符合React函数组件的开发规范,函数组件无法直接使用该挂载方法,大型项目不推荐使用。

内容的提问来源于stack exchange,提问作者Jamie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:54:03