如何在Reactjs中创建多步骤表单

时间:2020-07-25 13:10:32

标签: reactjs forms stepper

我们如何在Reactjs中创建多步骤表单作为多步骤表单提交器。目前,我没有显示每个步骤的组件

我想为每个步骤返回div组件,因为我无法为此应用逻辑。

现在我能够返回组件,但是它可以同时返回所有组件,因为我想一步一步返回中心

CodeSandbox Link

这是步进的代码

import React, { useState, useEffect } from "react";
import PropTypes from "prop-types";
import "./Stepper.scss";

const Stepper = ({ stepColor, steps, direction, currentStep }) => {
  const [stepState, setStepState] = useState([]);

  useEffect(() => {
    let createSteps = steps.map((step, idx) => ({
      description: step.label,
      component: step.component,
      completed: idx < currentStep - 1, // past are completed
      selected: idx <= currentStep - 1, // past & present are colored
      highlighted: idx === currentStep - 1 // only present is highlighted
    }));

    setStepState(createSteps);
  }, [steps, currentStep]);

  return (
    <div className={`stepper-wrapper-${direction}`}>
      {stepState.map(
        ({ selected, completed, highlighted, description, component }, idx) => (
          <div className="step-wrapper" key={idx}>
            <div
              className={`step-number step-number-${
                selected ? "active" : "disabled"
              }`}
              style={{ background: `${selected ? stepColor : "none"}` }}
            >
              {completed ? "✔" : idx + 1}
            </div>
            <div
              className={`step-description ${
                highlighted ? "step-description-active" : ""
              }`}
            >
              {description}
            </div>
            {idx + 1 !== stepState.length && (
              <div
                className={`divider-line divider-line-${stepState.length}`}
              />
            )}
            <div>{component}</div>
          </div>
        )
      )}
    </div>
  );
};

Stepper.propTypes = {
  direction: PropTypes.string.isRequired,
  steps: PropTypes.array.isRequired
};

export default Stepper;


enter image description here

1 个答案:

答案 0 :(得分:0)

我发现您的代码框上有一个奇怪的地方是您在<Stepper/>组件中提供的道具是错误的

  <div className="stepper-container-horizontal">
    <Stepper
      direction="horizontal"
      currentStepNumber={state.currentStep - 1}
      steps={stepsArray}
      stepColor="purple"
    />
  </div>

您正在传递到currentStepNumber,但是Step组件正在接受currentStep

在这一行

const Stepper = ({ stepColor, steps, direction, currentStep = 1 }) => {...

我确实将currentStepNumber更改为currentStep,并且现在正在工作。