Form.List +table 实现行内表格直接编辑以及删除功能
import React from 'react';
import { PlusOutlined, } from '@ant-design/icons';
import { Button, Form, Input, Space, Table } from 'antd';
const mockData = [
{
name: '糖果',
code: 'code1',
},
{
name: '饮料',
code: 'code2'
}
]
interface Iprops {
onCancel: () => void
onSumbit: () => void
type: 'add' | 'edit' | 'show'
data: []
}
const App = ({ onCancel, onSumbit, type, data }: Iprops) => {
const [form] = Form.useForm();
const disbled = type === 'show'
const onFinish = (values: any) => {
console.log('表单数据', values);
};
const columns = [
{
title: "名称",
dataIndex: 'name',
render(_, field) {
const name = form.getFieldValue(['users', field.name, 'name']);
return (
<Form.Item required name={[field?.name, 'name']} noStyle>
{
type !== 'show' ? <Input allowClear placeholder='请输入' disabled={disbled} /> : name
}
</Form.Item>
)
}
},
{
title: "code",
dataIndex: 'code',
render(_, field) {
const name = form.getFieldValue(['users', field.name, 'code']);
return (
<Form.Item required name={[field?.name, 'code']} noStyle>
{
type !== 'show' ? <Input allowClear placeholder='请输入' disabled={disbled} /> : name
}
</Form.Item>
)
}
},
]
if (type !== 'show') {
columns.push({
title: "操作",
dataIndex: '',
render: (_, field) => {
return (
<Space>
<a onClick={() => field.remove(field?.name)}>删除</a>
</Space>
);
},
})
}
return (
<Form
form={form}
initialValues={{ users: mockData }}
onFinish={onFinish}
style={{ maxWidth: 800 }}
>
<Form.List name="users">
{(fields, { add, remove }, { errors }) => (
<>
<Table
dataSource={fields?.map((i) => ({ ...i, remove }))}
columns={columns}
rowKey='key'
/>
<Form.Item>
<Button
type="dashed"
style={{ width: '100%', marginTop: '8px' }}
icon={<PlusOutlined />}
onClick={() => { add() }}
>
添加一行
</Button>
</Form.Item>
</>
)}
</Form.List>
<Form.Item>
<Button type="primary" htmlType="submit">
提交
</Button>
</Form.Item>
</Form>
);
};
export default App;