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

如何在带constructor的React类组件中使用react-i18next的t()函数?

报错原因

TS2345报错的本质是类型定义不匹配:withTranslation HOC 会自动向内部组件注入t、tReady属性,这部分属性不需要外部调用方传入。你之前直接让ExampleProps继承WithTranslation,相当于要求外部调用组件时必须传入t和tReady,和HOC的注入逻辑冲突,添加constructor后TS对构造函数入参的校验逻辑更严格,因此触发了类型错误。

支持constructor的实现方案

核心是拆分「对外暴露的自定义props」和「组件内部可用的props」,通过withTranslation的泛型声明告知TS哪些属性是外部传入的,哪些是HOC注入的,完整可运行代码如下:

import React from 'react';
import { WithTranslation, withTranslation } from "react-i18next";

// 定义组件对外接收的自定义属性,不需要包含i18next注入的属性
interface ExampleOwnProps {
  // 可自由添加自定义属性,外部调用时必须传入
  newProperty: string;
}

// 组件内部使用的props = 自定义属性 + i18next注入的属性
type ExampleProps = ExampleOwnProps & WithTranslation;

interface ExampleState {
  // 你的state定义
}

class Example extends React.Component<ExampleProps, ExampleState> {
  constructor(props: ExampleProps, context: any) {
    super(props, context);
    // 可正常初始化state,也可直接调用this.props.t
    this.state = {
      // state初始化逻辑
    }
  }

  render() {
    const { t } = this.props;
    return (
      <div>
        <p>{t('Test')}</p>
        <p>{this.props.newProperty}</p>
      </div>
    );
  }
}

// 给withTranslation指定自定义props的泛型,告诉TS对外导出的组件仅需传入ExampleOwnProps中的属性
export default withTranslation<ExampleOwnProps>()(Example);

如果你的组件不需要自定义外部属性,把ExampleOwnProps设为空对象,withTranslation泛型传入{}即可。

该方案可以同时满足:

  • 正常使用constructor初始化state
  • 可以直接访问this.props.t,无属性不存在报错
  • 自定义属性校验正常,无类型不兼容错误
  • 不需要通过i18n?.t调用,不会触发可能为undefined的报错

内容的提问来源于stack exchange,提问作者szab.kel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:57:03