Form.Item
中使用 valuePropName
来指定子节点的值的属性,例如Table
的数据源为dataSource
,Switch
的数据源是checked
- 在
Table
的columns
中定义需要表单控制的数据,render
返回Form.Item
import { Button, Form, Input, Table } from 'antd'
import React, { useEffect } from 'react'
const About: React.FC = (props: any) => {
const [form] = Form.useForm()
const columns: any = [
{
title: '姓名',
dataIndex: 'name',
key: 'name'
},
{
title: '年龄',
dataIndex: 'age',
key: 'age',
render: (text: any, record: any, index: number) => {
return (
<Form.Item name={['table', index, 'age']}>
<Input placeholder="请输入年龄" />
</Form.Item>
)
}
},
{
title: '住址',
dataIndex: 'address',
key: 'address'
}
]
useEffect(() => {
form.setFieldsValue({
table: [
{
key: '1',
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号'
},
{
key: '2',
name: '胡彦祖',
age: 42,
address: '西湖区湖底公园1号'
}
]
})
}, [])
const onFinish = (values: any) => {
console.log(values)
// 打印结果
/*
{
table: [
{
key: '1',
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号'
},
{
key: '2',
name: '胡彦祖',
age: 42,
address: '西湖区湖底公园1号'
}
]
}
*/
}
return (
<Form form={form} onFinish={onFinish}>
<Form.Item name="table" valuePropName="dataSource">
<Table bordered columns={columns} pagination={false} />
</Form.Item>
<Form.Item>
<Button htmlType="submit" type="primary">
Submit
</Button>
</Form.Item>
</Form>
)
}
export { About }
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/74b22dafc7564701700adfc56b41be6b.png#pic_center)