在Ant Design中,如果你想要提交一个表单,其中包含表格(Table)中的数据,你可以使用Form组件和Table组件的特性来实现。以下是一个简单的例子,展示了如何提交一个包含表格数据的表单:
jsx
import React from 'react';
import { Form, Button, Table, Input, Space } from 'antd';
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: (text, record, index) => (
<Form.Item name={`rows[${index}].name`}>
<Input value={text} />
</Form.Item>
),
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
render: (text, record, index) => (
<Form.Item name={`rows[${index}].age`}>
<Input value={text} />
</Form.Item>
),
},
];
const data = [
{
key: '1',
name: 'John Brown',
age: 32,
},
{
key: '2',
name: 'Jim Green',
age: 42,
},
];
const App = () => {
const onFinish = (values) => {
console.log('Received values of form: ', values);
// 提交表单数据到服务器
};
return (
<Form
onFinish={onFinish}
layout="inline"
>
<Form.List name="rows">
{(fields, { add, remove }) => (
<>
<Table
columns={columns}
dataSource={data}
rowKey="key"
pagination={false}
/>
<Space>
<Button onClick={() => add()}>Add Row</Button>
<Button type="primary" htmlType="submit">Submit</Button>
</Space>
</>
)}
</Form.List>
</Form>
);
};
export default App;
在这个例子中,我们使用了Form.List来渲染一个表单字段的列表,其中字段的name属性是动态生成的,以便每行表格数据都能以数组的形式被提交。每个单元格中的输入框被包裹在Form.Item组件中,以便能够收集数据。当用户点击提交按钮时,表单的数据将被收集并通过onFinish回调函数发送到服务器。