如何使用antd4 实现 分步表单

4,292 阅读1分钟

背景:

最近有同学说了一个分步骤的问题,然后回想以前有做过类似的项目,就将一些demo的代码贴出来,希望对道友们有所帮助。

贴个阿里云上的集群创建的页面

链接: sofa.console.aliyun.com/?spm=5176.2…

demo代码实现

import React, { useState, useEffect } from 'react';
import { Steps, Button, Space, Form, message } from 'antd';
import { useRequest } from 'ahooks';
import Basic from './Basic';   // 第一步的组件
import Node from './Node';    // 
import PreCheck from './PreCheck'; // 
import PostCheck from './PostCheck'; // 
// import Creating from './Creating';
import styles from './style.less';

const { Step } = Steps;
const StepComponents = [PreCheck, Basic, Node, PostCheck];

const ClusterForm = ({ dispatch }) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [form] = Form.useForm();
  const stepComponents = StepComponents;
  const stepLength = stepComponents.length;

  const createCluster = (payload) => {
    return 请求偶 promise
  };

  const { loading, run } = useRequest(createCluster, {
    manual: true,
    onSuccess: (result, params) => {
      console.log(result, params, 'mmmmmmmmm');
      if (result.resultCode === 'OK') {
        history.push(`/create/....`);
      } else {
        message.error(.....);
      }
    },
    onError: (error) => {
      message.error(error.message);
    },
  });

  const submit = () => {
    console.log(form.getFieldValue(), 'lllllll');
    // todo 表单提交后取到真实的opsId
    const handelFormData = form.getFieldValue();
    run(handelFormData);
  };

  const nextStep = (e) => {
    e.preventDefault();
    if (currentStep >= 0 && currentStep < stepLength - 1) {
      form
        .validateFields()
        .then((value) => {
          console.log(value, 'value');
          setCurrentStep(currentStep + 1);
        })
        .catch(() => {});
    }
  };

  const preStep = (e) => {
    e.preventDefault();
    if (currentStep > 0 && currentStep <= stepLength - 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const getStepComp = (step) => {
    const Comp = stepComponents[step];
    return <Comp form={form} />;
  };

  return (
    <div className={styles.clusterMain}>
      <div className={styles.clusterContainer}>
        <div className={styles.title}>changjian</div>
        {/* {!submitting && ( */}
        <div>
          <div className={styles.stepsContainer}>
            <Steps current={currentStep}>
              <Step title="1标题" />
              <Step title="2白天" />
              <Step title="3" />
              <Step title="4" />
            </Steps>
          </div>
          <div>{getStepComp(currentStep)}</div>
        </div>
        {/* )}
        {submitting && (
          <Creating
            goBack={() => {
              setSubmitting(false);
            }}
          />
        )} */}
      </div>
      {/* {!submitting && ( */}
      <div className={styles.stepsFooter}>
        <Space>
          {currentStep > 0 && <Button onClick={preStep}>上一步</Button>}
          {currentStep < stepLength - 1 && (
            <Button onClick={nextStep} type="primary">
              下一步
            </Button>
          )}
          {currentStep === stepLength - 1 && (
            <Button onClick={submit} style={{ width: '68px' }} type="primary" loading={loading}>
              提交
            </Button>
          )}
        </Space>
      </div>
      {/* )} */}
    </div>
  );
};

export default connect((state) => ({
  clusters: state.clusters,
}))(ClusterForm);

将每一步的页面都提取出来作为单独的组件,后续就可以非常好的维护,最后只需要将所有的数据收集过来一把提交就欧克了,是不是非常的不错偶!