我在使用 Material UI Stepper "Cannot read property stepIndex of undefined" 时遇到了一些奇怪的错误

Im getting some weird errors with MaterialUI Stepper "Cannot read property stepIndex of undefined"

我正在使用 MaterialUI,但出现错误 -

"Uncaught TypeError: Cannot read property 'stepIndex' of undefined" 在我的 Chrome 控制台中

我在使用任何其他 Material-UI React 组件时都没有遇到过这个错误。我是 React 的新手,所以如果这是一个愚蠢的错误,请多多包涵。 我似乎无法解决问题。

我正在使用 React 5.3.1。

我的代码:

class HorizontalLinearStepper extends React.Component {
  handleNext() {
    const {stepIndex} = this.state;
    this.setState({stepIndex: stepIndex + 1,finished: stepIndex >= 2});
  };
  handlePrev() {
    const {stepIndex} = this.state;
    if (stepIndex > 0) {
      this.setState({
        stepIndex: stepIndex - 1
      });
    }
  };

  getStepContent(stepIndex) {
    switch (stepIndex) {
      case 0:
        return 'Select campaign settings...';
      case 1:
        return 'What is an ad group anyways?';
      default:
        return 'You\'re a long way from home sonny jim!';
    }
  }
  render() {
    const {finished, stepIndex} = this.state;
    return (
      <div>
        <Stepper activeStep={stepIndex}>
          <Step>
            <StepLabel>Select campaign settings</StepLabel>
          </Step>
          <Step>
            <StepLabel>Create an ad group</StepLabel>
          </Step>
        </Stepper>
        <div style={contentStyle}>
          {finished ? (
            <p>
              <a
                href="#"
                onClick={(event) => {
                  event.preventDefault();
                  this.setState({stepIndex: 0, finished: false});
                }}
              >
                Click here
              </a> to reset the example.
            </p>
          ) : (
            <div>
              <p>{this.getStepContent(stepIndex)}</p>
              <div style={{marginTop: 12}}>
                <FlatButton
                  label="Back"
                  disabled={stepIndex === 0}
                  onTouchTap={this.handlePrev}
                  style={{marginRight: 12}}
                />
                <RaisedButton
                  label={stepIndex === 2 ? 'Finish' : 'Next'}
                  primary={true}
                  onTouchTap={this.handleNext}
                />
              </div>
            </div>
          )}
        </div>
      </div>
    );
  }
}
export default HorizontalLinearStepper;

谢谢!

<FlatButton
  label="Back"
  disabled={stepIndex === 0}
  onTouchTap={this.handlePrev.bind(this)}
  style={{marginRight: 12}}
/>
<RaisedButton
  label={stepIndex === 2 ? 'Finish' : 'Next'}
  primary={true}
  onTouchTap={this.handleNext.bind(this)}
/>

您需要绑定处理程序,因为它们将 运行 在不同的上下文中,并且会失去 this 的正确含义,因此我们绑定处理程序以保持 [=] 的正确上下文11=].