0
点赞
收藏
分享

微信扫一扫

Antd中Form表单与Table表格联合的简易使用

一世独秀 2022-03-18 阅读 80
  1. Form.Item 中使用 valuePropName 来指定子节点的值的属性,例如Table的数据源为dataSourceSwitch的数据源是checked
  2. Tablecolumns中定义需要表单控制的数据,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 }

在这里插入图片描述

举报

相关推荐

0 条评论