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

React组件调用方法时props undefined 无法读取activeStep属性报错

问题原因

核心问题是父组件SlidingWizardComponent传给子组件的setActiveStep方法丢失了自身的this指向,方法执行时访问this.props时this为undefined,所以触发Cannot read property 'activeStep' of undefined报错。

普通类方法在直接作为prop传递时,会脱离原组件的实例上下文,你代码中getWizard用箭头函数定义就没有这个问题,箭头函数会自动绑定定义时所在的上下文this。

修复方案

1. 修复this指向问题(二选一即可)

方案A:将父组件的setActiveStep改为箭头函数

把SlidingWizardComponent中的普通方法改为箭头函数,自动绑定this:

// 修改前是 private setActiveStep(clickedStep: number): void {
private setActiveStep = (clickedStep: number): void => {
    if (clickedStep !== this.props.activeStep) {
        this.props.setActiveStep(clickedStep);
    }
}

方案B:传递方法时手动绑定this

在createWizard方法传递prop时,用bind绑定父组件实例的this:

wizardSteps.push(
    <SlidingWizardStepComponent setActiveStep={this.setActiveStep.bind(this)} />
);

2. 修复其他代码错误

你的代码还存在几处遗漏会导致后续报错,需要同步修复:

  • 父组件getWizard方法存在语法错误,去掉多余的等于号:
    // 修改前是 return = this.createWizard();
    return this.createWizard();
    
  • 父组件SlidingWizardComponentProps接口补充缺失的属性声明:
    export interface SlidingWizardComponentProps {
        activeStep: number;
        numberOfSteps: number; // 新增:循环逻辑用到了这个属性
        setActiveStep: (clickedStep: number) => void; // 新增:方法内调用了这个属性
    }
    
  • 上层组件调用SlidingWizardComponent时补传缺失的props:
    <SlidingWizardComponent
        activeStep={this.state.activeStep}
        setActiveStep={this.setActiveStep} // 新增:把上层的setActiveStep传给父组件
        numberOfSteps={5} // 替换为你实际的步骤数,可从上层props获取
    />
    
  • 父组件循环创建子组件时补传stepIndex,子组件Props接口同步补充声明:
    父组件createWizard里修改:
    wizardSteps.push(
        <SlidingWizardStepComponent 
            setActiveStep={this.setActiveStep}
            stepIndex={i} // 新增:把当前循环的索引传给子组件
        />
    );
    
    子组件Props接口补充:
    export interface SlidingWizardStepComponentProps {
        setActiveStep: (clickedStep: number) => void;
        stepIndex: number; // 新增:子组件逻辑用到了这个属性
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:06:01