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

React类组件中如何正确使用react-i18next的useTranslation Hook

错误原因

useTranslation 是React专属Hook,仅允许在函数组件、自定义Hook的内部调用,你在类组件外部直接调用Hook不符合React的使用规则,因此无法正常获取t和i18n实例。

解决方法

使用react-i18next官方为类组件提供的withTranslation高阶组件适配,操作步骤如下:

  • 替换导入的useTranslation为withTranslation
  • 删除组件外部调用useTranslation的代码
  • 用withTranslation()包裹你的类组件,翻译相关的能力会自动注入到组件的props中
  • 类内部使用时直接从this.props取t和i18n即可
修改后的完整代码
import React, { Component } from 'react';
import { inject, observer } from "mobx-react";
// 替换导入为withTranslation
import { withTranslation } from 'react-i18next';

import Timer from '../../components/common/Timer';
import FrenchLanguage from '../../images/france-48.png';
import EnglishLanguage from '../../images/england-48.png';

import './brothers.scss';

// 类名首字母大写,符合React组件命名规范
class Brothers extends Component {
  constructor(props) {
    super(props);
    this.stores = this.props.Stores;
  }

  updateResponsive = () => {
    this.forceUpdate()
  }

  changeLanguage = (Language) => {
    // 从props中获取i18n实例
    this.props.i18n.changeLanguage(Language)
  }

  showAlert = () =>{
    // 后续需要翻译的文案直接调用this.props.t传入对应key即可
    alert("I'm an alert : " + this.props.t('your.translation.key'));
  }

  render() {
    return (
      <div className={"full-screen main-grid"}>
        <Timer
          task={this.updateResponsive}
          interval={1000}
        />
        <div className="title-containers">
          <div className="language">
            <img onClick={() => this.changeLanguage('fr')}  src={FrenchLanguage} alt="French"/>
            <img onClick={() => this.changeLanguage('en')}  src={EnglishLanguage} alt="English"/>
          </div>
        </div>
      </div>
    );
  }
}

// 导出时用withTranslation包裹组件,注意调用顺序
export default inject("Stores")(observer(withTranslation()(Brothers)));

如果你的多语言配置了独立命名空间,只需要在withTranslation的参数里传入对应的命名空间即可,比如withTranslation('common')。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:06:05