一、动态列表
动态列表Form.List是包含多个表单的情况,往往是多维数组数据,意思就是往往这个数据传递到后端是数组数据。
二、场景实现
实现效果
实现代码
import React from "react";
import _ from "lodash";
import "./index.less";
import { PlusCircleOutlined, CloseCircleFilled } from "@ant-design/icons";
import { Typography, Form, Input, Select, Space, Button } from "antd";
const App = () => {
const [form] = Form.useForm();
const onFinish = async () => {
const values = await form.validateFields();
console.log("Received values of form:", values);
};
return (
<Form
form={form}
layout="vertical"
name="dynamic_form_nest_item"
onFinish={onFinish}
autoComplete="off"
>
<Form.Item label="商品资源">
<Form.List name={"source"}>
{(fields, { add, remove }, { errors }) => (
<>
{fields.map((field) => (
<div className="source-list-item" key={field.key}>
<Space align="baseline">
<Form.Item
label="商品类别"
validateTrigger="onBlur"
name={[field.name, "resourcesCategory"]}
rules={[
{
validator: (dom, v) =>
_.isEmpty(v)
? Promise.reject("请选择商品类别")
: Promise.resolve()
}
]}
>
<Select
autoFocus
options={[
{ label: "果蔬鲜花", value: "果蔬鲜花" },
{ label: "肉禽蛋品", value: "肉禽蛋品" }
]}
></Select>
</Form.Item>
<Form.Item
label="商品ID"
name={[field.name, "resourcesId"]}
validateTrigger="onBlur"
rules={[
{
validator: (dom, v) =>
_.isEmpty(v)
? Promise.reject("请输入商品ID")
: Promise.resolve()
}
]}
>
<Input />
</Form.Item>
</Space>
<CloseCircleFilled
onClick={() => remove(field.name)}
style={{ padding: "10px" }}
/>
</div>
))}
<Form.ErrorList errors={errors} />
<Form.Item style={{ marginBottom: 0 }}>
<Typography.Link onClick={() => add()}>
<Space>
<PlusCircleOutlined /> 添加商品
</Space>
</Typography.Link>
</Form.Item>
</>
)}
</Form.List>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
export default App;
.source-list-item {
display: flex;
align-items: center;
margin-bottom: 10px;
> .ant-space {
display: flex;
width: 100%;
background: #f5f5f5;
padding: 10px 20px 0 30px;
> .ant-space-item {
flex: 1 1 50%;
}
}
}