【问题标题】:How to create multi-step form in Reactjs如何在 Reactjs 中创建多步表单
【发布时间】:2020-11-15 05:09:06
【问题描述】:

我们如何在 Reactjs 中创建多步表单的 stepper 以进行多步表单提交。目前我没有显示每个步骤的组件

我想为每个步骤返回 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;


【问题讨论】:

    标签: reactjs forms stepper


    【解决方案1】:

    我在您的代码盒中发现一件奇怪的事情是您在 &lt;Stepper/&gt; 组件中提供的道具是错误的

      <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 并且现在正在工作。

    【讨论】:

    • 嗨@keysl 对于每个步骤我如何添加显示一些细节的组件你能在这方面给出一些观点
    • hmmm,因为您正在通过 Parent(App.js) 组件 state 控制 Stepper,我认为在操作字段时使用 currentStep 状态。您的 Step 不应该关心任何其他组件,并且可以保持现在的状态。
    • 嗨@keysl 我也更新了我的代码和链接,请看一下
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多