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

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

话不多说,上代码

/*
 * 创建修改版本
 */
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) => (
      
        {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: "请输入有效的附件地址",
            }
          ],
        })()}
        {keys.length > 1 ? (
           this.remove(k)}
          />
        ) : null}
      
    ));
    return (
      
        
          
{getFieldDecorator("projectCode", { initialValue: taskModalType === "edit" ? versionInfo.projectCode : "", rules: [{ required: true, message: "请选择项目编码!" }], })( )} {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(); // } // } ], })( )} {getFieldDecorator("versionDepend", { initialValue: taskModalType === "edit" ? versionInfo.versionDepend : 1, rules: [{ required: true, message: "请选择是否依赖!" }], })( 存在依赖 不存在依赖 )} {getFieldDecorator("dependVersionNumList", { initialValue: taskModalType === "edit" ? versionInfo.dependVersionNumList : [], })( )} {getFieldDecorator("selfDependVersionNumList", { initialValue: taskModalType === "edit" ? versionInfo.selfDependVersionNumList : [], })( )} {getFieldDecorator("versionGeneral", { initialValue: taskModalType === "edit" ? versionInfo.versionGeneral : 1, rules: [{ required: true, message: "请选择是否通用!" }], })( 通用版本 非通用版本 )} {getFieldDecorator("deployFlag", { initialValue: taskModalType === "edit" ? versionInfo.deployFlag : 1, rules: [{ required: true, message: "请选择能否实施!" }], })( 不能实施 可实施 )} {getFieldDecorator("demandCode", { initialValue: taskModalType === "edit" ? versionInfo.demandCode : "", })( )} {getFieldDecorator("note", { initialValue: taskModalType === "edit" ? versionInfo.note : "", })( )} {formItems}
); } } const View = Form.create()(ViewForm); export default View;

 

你可能感兴趣的:(antd,antd,antd-form)