import React, { useState } from 'react';
import { Table, Input, InputNumber, Popconfirm, Form, Select } from 'antd';
const { Option } = Select;
const EditableCell = ({ editing, dataIndex, title, inputType, record, index, children, ...restProps }) => {
let inputNode;
if (inputType === 'number') {
inputNode = <InputNumber />;
} else if (inputType === 'select') {
inputNode = (
<Select>
<Option value="Option 1">Option 1</Option>
<Option value="Option 2">Option 2</Option>
<Option value="Option 3">Option 3</Option>
</Select>
);
} else {
inputNode = <Input />;
}
return (
<td {...restProps}>
{editing ? (
<Form.Item
name={dataIndex}
style={{ margin: 0 }}
rules={[
{
required: true,
message: `Please Input ${title}!`,
},
]}
>
{inputNode}
</Form.Item>
) : (
children
)}
</td>
);
};
const EditableTable = () => {
const [form] = Form.useForm();
const [data, setData] = useState([
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
]);
const [editingKey, setEditingKey] = useState('');
const isEditing = (record) => record.key === editingKey;
const edit = (record) => {
form.setFieldsValue({
name: '',
age: '',
address: '',
...record,
});
setEditingKey(record.key);
};
const cancel = () => {
setEditingKey('');
};
const save = async (key) => {
try {
const row = await form.validateFields();
const newData = [...data];
const index = newData.findIndex((item) => key === item.key);
if (index > -1) {
const item = newData[index];
newData.splice(index, 1, { ...item, ...row });
setData(newData);
setEditingKey('');
} else {
newData.push(row);
setData(newData);
setEditingKey('');
}
} catch (errInfo) {
console.log('Validate Failed:', errInfo);
}
};
const columns = [
{
title: 'Name',
dataIndex: 'name',
width: '25%',
editable: true,
},
{
title: 'Age',
dataIndex: 'age',
width: '15%',
editable: true,
},
{
title: 'Address',
dataIndex: 'address',
width: '40%',
editable: true,
},
{
title: 'operation',
dataIndex: 'operation',
render: (_, record) => {
const editable = isEditing(record);
return editable ? (
<span>
<a href="javascript:;" onClick={() => save(record.key)}>
Save
</a>
<Popconfirm title="Sure to cancel?" onConfirm={cancel}>
<a>Cancel</a>
</Popconfirm>
</span>
) : (
<a disabled={editingKey !== ''} onClick={() => edit(record)}>
Edit
</a>
);
},
},
];
const mergedColumns = columns.map((col) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record) => ({
record,
inputType: col.dataIndex === 'age' ? 'number' : (col.dataIndex === 'address' ? 'select' : 'text'),
dataIndex: col.dataIndex,
title: col.title,
editing: isEditing(record),
}),
};
});
return (
<Form form={form} component={false}>
<Table
components={{
body: {
cell: EditableCell,
},
}}
bordered
dataSource={data}
columns={mergedColumns}
rowClassName="editable-row"
pagination={{
onChange: cancel,
}}
/>
</Form>
);
};
export default EditableTable;
Ant-Design Table可编辑行增加下拉框
最新推荐文章于 2024-07-30 11:11:00 发布