是的,可以向Antd表格添加可编辑的行。Antd是一个基于React的UI组件库,提供了丰富的组件和功能,包括表格组件。在Antd表格中,可以通过设置editable
属性来实现行的可编辑性。
具体步骤如下:
dataSource
和columns
属性来定义表格的数据源和列。editable
属性为true
。Input
、Select
等组件来实现不同类型的编辑输入框。以下是一个示例代码:
import React, { useState } from 'react';
import { Table, Input, Select } from 'antd';
const EditableTable = () => {
const [dataSource, setDataSource] = useState([
{ id: 1, name: 'John', age: 25 },
{ id: 2, name: 'Jane', age: 30 },
]);
const [editingId, setEditingId] = useState('');
const handleEdit = (record) => {
setEditingId(record.id);
};
const handleSave = (record) => {
// 保存编辑后的数据
setEditingId('');
};
const columns = [
{ title: 'ID', dataIndex: 'id' },
{
title: 'Name',
dataIndex: 'name',
editable: true, // 设置可编辑
render: (text, record) =>
editingId === record.id ? (
<Input value={text} onChange={(e) => handleInputChange(e, record)} />
) : (
text
),
},
{
title: 'Age',
dataIndex: 'age',
editable: true, // 设置可编辑
render: (text, record) =>
editingId === record.id ? (
<Select value={text} onChange={(value) => handleSelectChange(value, record)}>
<Select.Option value="25">25</Select.Option>
<Select.Option value="30">30</Select.Option>
<Select.Option value="35">35</Select.Option>
</Select>
) : (
text
),
},
{
title: 'Operation',
render: (_, record) => {
const isEditing = editingId === record.id;
return isEditing ? (
<a onClick={() => handleSave(record)}>Save</a>
) : (
<a onClick={() => handleEdit(record)}>Edit</a>
);
},
},
];
const handleInputChange = (e, record) => {
const { value } = e.target;
setDataSource((prevDataSource) =>
prevDataSource.map((item) =>
item.id === record.id ? { ...item, name: value } : item
)
);
};
const handleSelectChange = (value, record) => {
setDataSource((prevDataSource) =>
prevDataSource.map((item) =>
item.id === record.id ? { ...item, age: value } : item
)
);
};
return <Table dataSource={dataSource} columns={columns} />;
};
export default EditableTable;
在上述示例中,我们创建了一个可编辑的表格,其中Name和Age列设置了editable
属性为true
,并分别使用Input
和Select
组件来实现编辑输入框。点击Edit按钮可以进入编辑模式,点击Save按钮可以保存编辑后的数据。
这是一个简单的示例,你可以根据实际需求进行扩展和定制。如果你想了解更多Antd表格的用法和相关组件,请参考腾讯云Antd的官方文档:Antd - Table。
领取专属 10元无门槛券
手把手带您无忧上云