antd 表单动态添加表单项编辑回显数据

2023-05-16

在做一些后台管理会用到很多的表单,比如动态项表单,如下图这样的

话不多说,上代码

/*
 * 创建修改版本
 */
import React from "react";
import { Form, Notification, Button, Input, Row, Col, Select, Radio, Icon } from "antd";
import Request from "@utils/request";
import Storage from "store2";
import "./style.less";

const FormItem = Form.Item;
let id = 0;
class ViewForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      versionInfo: {}, // 编辑的初始数据
      demandCodeList: [], //需求编号
      projectCodeList: [], //项目编号
      versionCodeList: [] //依赖的版本编号
    };
  }
  componentDidMount() {
    this.getDemandCodeList();
    this.getProjectCodeList();
    this.getVersionCodeList();
    const { taskModalType } = this.props;
    if (taskModalType === "edit") {
      this.loadData()
    }
  }
  // 获取版本信息
  loadData = async () => {
    Request.GET(`/api/version/get/${this.props.versionInfo.id}`, {
      params: {
        loginKey: Storage.get("Authorization"),
      }
    }).then((res) => {
      if (res.success) {
        this.setState({
          versionInfo: res.data
        });
      } else {
        Notification.warning({
          message: res.msg || "获取版本信息失败",
        });
      }
    });
  };
  // 获取依赖的版本编号列表
  getVersionCodeList = () => {
    Request.GET("/api/version/list", {
      params: {
        loginKey: Storage.get("Authorization"),
      }
    }).then((res) => {
      if (res.success) {
        this.setState({
          versionCodeList: res.data
        });
      } else {
        Notification.warning({
          message: res.msg || "获取需求编号列表",
        });
      }
    });
  };
  // 获取需求编号列表
  getDemandCodeList = () => {
    Request.GET("/api/demand/list", {
      params: {
        loginKey: Storage.get("Authorization"),
      }
    }).then((res) => {
      if (res.success) {
        this.setState({
          demandCodeList: res.data
        });
      } else {
        Notification.warning({
          message: res.msg || "获取需求编号列表",
        });
      }
    });
  };
  // 获取项目列表
  getProjectCodeList = () => {
    // 获取任务列表
    Request.GET("/api/project/list", {
      params: {
        loginKey: Storage.get("Authorization"),
      }
    }).then((res) => {
      if (res.success) {
        this.setState({
          projectCodeList: res.data
        });
      } else {
        Notification.warning({
          message: res.msg || "获取项目列表失败",
        });
      }
    });
  }
  handleSubmit = () => {
    const { form: { validateFields }, taskModalType } = this.props;
    const { versionInfo } = this.state;
    validateFields((err, values) => {
      if (!err) {
        const { names } = values;
        console.log("names=",names);
        const urlList = names;
        if (taskModalType === "edit") {
          Request.POST("/api/version/update", {
            params: {
              loginKey: Storage.get("Authorization"),
            },
            body: {
              "id": versionInfo.id,
              "demandCode": values.demandCode,
              "dependVersionNumList": values.dependVersionNumList,
              "selfDependVersionNumList": values.selfDependVersionNumList,
              "projectCode": values.projectCode,
              "versionDepend": values.versionDepend,
              "versionGeneral": values.versionGeneral,
              "versionNum": values.versionNum,
              "deployFlag": values.deployFlag,
              "note": values.note,
              "fileUrlList": urlList
            }
          }).then((res) => {
            if (res.success) {
              Notification.success({
                message: res.msg || "修改成功",
              });
              this.props.parentThis.CancelTaskModal();
              this.props.parentThis.loadData();
            } else {
              Notification.warning({
                message: res.msg || "修改失败",
              });
            }
          });
        } else {
          Request.POST("/api/version/add", {
            params: {
              loginKey: Storage.get("Authorization"),
            },
            body: {
              "demandCode": values.demandCode,
              "dependVersionNumList": values.dependVersionNumList,
              "selfDependVersionNumList": values.selfDependVersionNumList,
              "projectCode": values.projectCode,
              "versionDepend": values.versionDepend,
              "versionGeneral": values.versionGeneral,
              "versionNum": values.versionNum,
              "deployFlag": values.deployFlag,
              "note": values.note,
              "fileUrlList": urlList
            }
          }).then((res) => {
            if (res.success) {
              Notification.success({
                message: res.msg || "新增版本成功",
              });
              this.props.parentThis.CancelTaskModal();
              this.props.parentThis.loadData();
            } else {
              Notification.warning({
                message: res.msg || "新增版本失败",
              });
            }
          });
        }
      }
    });
  };
  remove = k => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue("keys");
    // We need at least one passenger
    if (keys.length === 1) {
      return;
    }
    // can use data-binding to set
    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  };
  add = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue("keys");
    const nextKeys = keys.concat(id);
    id++;
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      keys: nextKeys,
    });
  };
  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { taskModalType } = this.props;
    const { versionInfo, demandCodeList, projectCodeList, versionCodeList } = this.state;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
    };
    // 添加附件地址
    const formItemLayoutWithOutLabel = {
      wrapperCol:  {span: 18, offset: 5 },
    };
    getFieldDecorator("keys", { initialValue: versionInfo.fileUrlList ? versionInfo.fileUrlList : [] });
    const keys = getFieldValue("keys") ? getFieldValue("keys") : [];
    console.log(versionInfo, keys);
    const formItems = keys.map((k, index) => (
      <Form.Item
        {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
        label={index === 0 ? "附件地址" : ""}
        required={false}
        key={k}
      >
        {getFieldDecorator(`names[${index}]`, {
          initialValue: Number.isInteger(k) ? "" : k,
          validateTrigger: ["onChange", "onBlur"],
          rules: [
            {
              required: true,
              whitespace: true,
              message: "请输入附件地址",
            },
            {
              pattern: /^(ht|f)tps?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?([a-zA-Z0-9_-]|#|%)(\?)?)*)*$/i,
              message: "请输入有效的附件地址",
            }
          ],
        })(<Input placeholder="请输入有效的附件地址"
          style={{ width: "90%", marginRight: 2 }} />)}
        {keys.length > 1 ? (
          <Icon
            className="dynamic-delete-button"
            type="minus-circle-o"
            onClick={() => this.remove(k)}
          />
        ) : null}
      </Form.Item>
    ));
    return (
      <Row>
        <Col>
          <Form>
            <FormItem label="项目编码"
              {...formItemLayout}
            >
              {getFieldDecorator("projectCode", {
                initialValue: taskModalType === "edit" ? versionInfo.projectCode : "",
                rules: [{ required: true, message: "请选择项目编码!" }],
              })(
                <Select
                  showSearch
                  placeholder="请选择项目编码"
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children.indexOf(input) >= 0
                  }
                >
                  {
                    projectCodeList.map((item, index) => {
                      return <Select.Option
                        value={item.projectCode}
                        key={index}
                      >
                        {`${item.projectName}-${item.projectCode}`}
                      </Select.Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
            <FormItem label="版本号"
              {...formItemLayout}
            >
              {getFieldDecorator("versionNum", {
                initialValue: taskModalType === "edit" ? versionInfo.versionNum : "",
                rules: [
                  { required: true, message: "请填写版本号(项目+编号)!" },
                  // {
                  //   validator: (rule, value, callback) => {
                  //     if (!/^[\u4e00-\u9fa50-9a-zA-Z.]*$/.test(value)) {
                  //       callback("版本号仅包含汉字数字、英文、和.");
                  //     }
                  //     callback();
                  //   }
                  // }
                ],
              })(
                <Input placeholder="请填写版本号(项目+编号)" />
              )}
            </FormItem>
            <FormItem label="是否依赖"
              {...formItemLayout}
            >
              {getFieldDecorator("versionDepend", {
                initialValue: taskModalType === "edit" ? versionInfo.versionDepend : 1,
                rules: [{ required: true, message: "请选择是否依赖!" }],
              })(
                <Radio.Group >
                  <Radio value={1}>存在依赖</Radio>
                  <Radio value={2}>不存在依赖</Radio>
                </Radio.Group>
              )}
            </FormItem>
            <FormItem label="依赖的版本号"
              {...formItemLayout}
            >
              {getFieldDecorator("dependVersionNumList", {
                initialValue: taskModalType === "edit" ? versionInfo.dependVersionNumList : [],
              })(
                <Select
                  showSearch
                  mode="multiple"
                  placeholder="请选择依赖的版本号"
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children.indexOf(input) >= 0
                  }
                >
                  {
                    versionCodeList.map((item, index) => {
                      return <Select.Option
                        value={item.versionNum}
                        key={index}
                      >
                        {item.versionNum}
                      </Select.Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
            <FormItem label="升级依赖版本"
              {...formItemLayout}
            >
              {getFieldDecorator("selfDependVersionNumList", {
                initialValue: taskModalType === "edit" ? versionInfo.selfDependVersionNumList : [],
              })(
                <Select
                  showSearch
                  mode="multiple"
                  placeholder="请选择升级依赖的版本号"
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children.indexOf(input) >= 0
                  }
                >
                  {
                    versionCodeList.map((item, index) => {
                      return <Select.Option
                        value={item.versionNum}
                        key={index}
                      >
                        {item.versionNum}
                      </Select.Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
            <FormItem label="是否通用"
              {...formItemLayout}
            >
              {getFieldDecorator("versionGeneral", {
                initialValue: taskModalType === "edit" ? versionInfo.versionGeneral : 1,
                rules: [{ required: true, message: "请选择是否通用!" }],
              })(
                <Radio.Group >
                  <Radio value={1}>通用版本</Radio>
                  <Radio value={2}>非通用版本</Radio>
                </Radio.Group>
              )}
            </FormItem>
            <FormItem label="能否实施"
              {...formItemLayout}
            >
              {getFieldDecorator("deployFlag", {
                initialValue: taskModalType === "edit" ? versionInfo.deployFlag : 1,
                rules: [{ required: true, message: "请选择能否实施!" }],
              })(
                <Radio.Group >
                  <Radio value={1}>不能实施</Radio>
                  <Radio value={2}>可实施</Radio>
                </Radio.Group>
              )}
            </FormItem>
            <FormItem label="需求编号"
              {...formItemLayout}
            >
              {getFieldDecorator("demandCode", {
                initialValue: taskModalType === "edit" ? versionInfo.demandCode : "",
              })(
                <Select
                  showSearch
                  placeholder="请选择需求编号"
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children.indexOf(input) >= 0
                  }
                >
                  {
                    demandCodeList.map((item) => {
                      return <Select.Option
                        value={item.demandCode}
                        key={item.id}
                      >
                        {`${item.demandName}-${item.demandCode}`}
                      </Select.Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
            <FormItem label="备注"
              {...formItemLayout}
            >
              {getFieldDecorator("note", {
                initialValue: taskModalType === "edit" ? versionInfo.note : "",
              })(
                <Input placeholder="请填写备注" />
              )}
            </FormItem>
            {formItems}
            <Form.Item
                {...formItemLayoutWithOutLabel}>
              <Button type="dashed"
                onClick={this.add}
                style={{ width: "50%" }}>
                <Icon type="plus" /> 添加附件地址
              </Button>
            </Form.Item>
          </Form>
        </Col>
        <Col style={{ "textAlign": "right" }}>
          <Button type="primary"
            htmlType="submit"
            onClick={() => {
              this.handleSubmit()
            }}
          >确定</Button>
          <Button style={{ "marginLeft": 8 }}
            onClick={() => {
              this.props.parentThis.CancelTaskModal();
            }}
          >取消</Button>
        </Col>
      </Row>
    );
  }
}

const View = Form.create()(ViewForm);
export default View;

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

antd 表单动态添加表单项编辑回显数据 的相关文章

随机推荐

  • 命令式与声明式 - 理解 k8s 声明式api工作原理 -Kubernetes 控制器的工作原理解读

    一 命令式和声明式 命令式 xff08 可以理解为 面向过程 xff09 编程 xff1a 命令 机器 如何去做事情 how xff0c 这样不管你想要的是什么 what xff0c 它都会按照你的命令实现 声明式 xff08 可以理解为
  • k8s自定义资源CRD

    原文 xff1a 1089条消息 k8s自定义资源CRD gogogo69的博客 CSDN博客 k8s 自定义crd https blog csdn net Jacson article details 125305201 一 概述 在K8
  • golang go语音 之 结构体

    一 结构体基础 Go语言中没有 类 的概念 xff0c 也不支持 类 的继承等面向对象的概念 Go语言中通过结构体的内嵌再配合接口比面向对象具有更高的扩展性和灵活性 go自定义类型 例如 xff1a 类型定义 打印出是 NewInt 类型
  • goroutine 调度器原理详解 - 进程 线程 协程 之 go语言篇

    一 先理解一下 进程和线程通俗易懂文章 xff1a 1122条消息 线程与进程 xff0c 你真得理解了吗 进程和线程 云深i不知处的博客 CSDN博客 什么是进程 先给一个定义 xff1a 进程是一个具有一定独立功能的程序在一个数据集合上
  • Go语言内存 Go内存 golang内存

    原文 xff1a 一文彻底理解Go语言栈内存 堆内存 360doc com 一 为什么计算机需要内存 代码的本质 xff1a 指令和数据 指令 xff1a 中央处理器CPU可执行的指令 数据部分 xff1a 常量变量等 代码包含了指令 xf
  • 如何卸载Ubuntu软件

    方法 1 使用Synaptic软件包管理器进行卸载 1 打开软件包管理器 Ubuntu自带了一个GUI xff08 Graphical User Interface xff0c 图形化用户界面 xff09 软件包管理器 xff0c 它可以让
  • operator-framework生态之operator-sdk入门和安装 operator实战

    推荐 近期推荐实战 20230424 kubebuilder实战 https www cnblogs com bolingcavalry archive 2021 08 25 15183342 html 推荐阅读 单个CRD所定义的能力是有
  • MATLAB求解接地金属槽内电位分布

    基于MATLAB有限差分法中的迭代法求解接地金属槽内电位分布 要求有限差分法MATLAB编写运行结果全部代码 要求 运用MATLAB求解接地金属槽内点位分布 xff0c 精度 行数M 列数N自己定义 有限差分法 有限差分法是基于差分原理的一
  • 51单片机水位检测

    基于单片机的楼顶水箱水位监控系统设计 大楼的楼顶水箱容量有限 xff0c 要求实时显示其水位 xff0c 自动开停水泵控制水位在合理范围 利用单片机为核心构成控制系统 xff0c 选择传感器检测水位 水泵电机温度 xff08 防止过热损坏
  • 关于HC05 蓝牙模块与与蓝牙模块连接

    两个蓝牙模块配对通信 在通常的电子设计中 xff0c 一般采用蓝牙模块与上位机 xff08 手机 xff09 连接来与电子设备通信 xff0c 实现对电子设备的控制 当然也可以通过WiFi模块等其他通信模块进行通信 这里就介绍一下蓝牙模块之
  • Gazebo配置与控制不同的无人机 仿真

    PX4 Firmware 配置与控制不同的无人机 配置方法控制方法 XTDrone目前支持多旋翼飞行器 xff08 multirotor xff09 固定翼飞行器 xff08 plane xff09 可垂直起降固定翼飞行器 xff08 vt
  • 基于采样的路径规划算法RRT的优化:RRT*,Kinodynamic-RRT*,Anytime-RRT *,Informed RRT *

    基于采样的路径规划算法RRT的优化 RRT 算法Kinodynamic RRT Anytime RRT Informed RRT 关于搜索树按搜索方向生长的计算方法 基本的基于采样的路径规划算法RRT xff0c 在地图中进行采样取点 xf
  • 碰到的bug,解决方法

    问题解决 1 build Error Unable to find source space home xxx src 在新建的工作空间下进行 catkin build 编译工作空间 xff0c 工作空间下没有产生 devel logs b
  • Geometrically Constrained Trajectory Optimization for Multicopters 论文解析

    关于多旋翼几何约束轨迹优化 MINCO 轨迹类几何约束实验 Geometrically Constrained Trajectory Optimization for Multicopters 一文由浙江大学博士 汪哲培 2022年发表在I
  • Fast-planner 和 Ego-planner 比较

    Fast planner 和 Ego planner 比较 Fast PlannerEgo planner Fast planner和Ego planner都是无人机路径规划中常见的算法 xff0c 但它们的实现方式和目标略有不同 Fast
  • Teach-Repeat-Replan: A Complete and Robust System for Aggressive Flight in Complex Environments 论文笔记

    Teach Repeat Replan 飞行走廊生成方法凸多面体膨胀CPU加速GPU加速飞行走廊生成与环路消除 时空全局轨迹优化空间轨迹优化时间轨迹优化 在线局部重规划局部重规划框架 飞行走廊生成方法 围绕 teaching traject
  • ovn实验手册

    参考文档 openstack ovn结合官方文档 ovn实践参考
  • 蓝桥杯 小数第n位 问题的几种解法

    蓝桥杯 小数第n位 问题的几种解法 题目描述解法1 根据手动计算除法的过程 题目描述 我们知道 xff0c 整数做除法时 xff0c 有时得到有限小数 xff0c 有时得到无限循环小数 如果我们把有限小数的末尾加上无限多个 0 xff0c
  • 解决Vmware虚拟机无法打开Ubuntu的问题

    1 xff0c 问题 很多同学会在Window PC机上使用Vmware虚拟机来搭建Linux开发环境 xff08 如Ubuntu xff09 xff0c 使用过程中难免会出现Ubuntu崩溃 异常关闭等现象 xff0c 此时 xff0c
  • antd 表单动态添加表单项编辑回显数据

    在做一些后台管理会用到很多的表单 xff0c 比如动态项表单 xff0c 如下图这样的 话不多说 xff0c 上代码 创建修改版本 import React from 34 react 34 import Form Notification