我在使用MaterialUI Stepper时遇到了一些奇怪的错误"无法读取未定义的属性stepIndex"

时间:2016-09-09 22:38:02

标签: material-ui

我使用的是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;

谢谢!

1 个答案:

答案 0 :(得分:0)

<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的正确含义,因此我们绑定处理程序以保持this的正确上下文。