首页 > 解决方案 > 创建 Stepper,将 next 和 back 作为 onClick-event 处理

问题描述

我想创建一个步进器,您可以在其中将 StepLabel 中的 Next 和 handleBack 作为 onClickevent 处理。我不知道该怎么做。

这是沙箱:https ://codesandbox.io/s/stepper-forked-2q1wd

export default function IndexPage() {
  const [activeStep, setActiveStep] = useState(0);

  const handleNext = () => {
    setActiveStep((prevActiveStep) => prevActiveStep + 1);
  };

  const handleBack = () => {
    setActiveStep((prevActiveStep) => prevActiveStep - 1);
  };

  function getStepsContent(stepIndex) {
    switch (stepIndex) {
      case 0:
        return <h1>adsf</h1>;
      case 1:
        return <h1>adsf</h1>;
      case 2:
        return <h1>adsf</h1>;
    }
  } 
const steps = getSteps();
  return (
    <>
      <div>
        <Stepper
          alternativeLabel
          activeStep={activeStep}
          connector={<ColorlibConnector />}
        >
          {steps.map((label) => (
            <Step key={label}>
              <StepLabel
                onClick={handleNext}
                StepIconComponent={ColorlibStepIcon}
              >
                {label}
              </StepLabel>
            </Step>
          ))}
        </Stepper>
      </div>
      <br />

      <div>
        {getStepsContent(activeStep)}

       
        {activeStep === steps.length ? (
          "Bewerbung abgesendet"
        ) : (
          <div style={{ display: "flex", justifyContent: "center" }}>
            <div>
              <Button
                variant="outlined"
                color="primary"
                onClick={handleBack}
                disabled={activeStep === 0}
              >
               {activeStep > 0 ? "Zurück" : null}
              </Button>

              <Button
                style={{ color: "white", margin: 30 }}
                variant="contained"
                color="primary"
                onClick={handleNext}
              >
                {activeStep === steps.length - 1 ? "Absenden" : "Weiter"}
              </Button>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

我刚刚将handleNext 函数添加为onClick,但我还想通过单击步进器返回。

标签: reactjsmaterial-uinext.js

解决方案


您可以使用索引来设置步骤。用这个替换你onClickStepLabel

{steps.map((label, index) => (
            <Step key={label}>
              <StepLabel
                onClick={() => setActiveStep(index)}
                StepIconComponent={ColorlibStepIcon}
              >
                {label}
              </StepLabel>
            </Step>
         ))}

步进器 StepLabel 修复


推荐阅读