React Antd 表格:实现可编辑自定义行,自定义行无数据显示表格样式
React Antd 表格:实现可编辑自定义行,自定义行无数据显示表格样式
本文将详细介绍如何在 Ant Design 的 Table 组件中实现每一条数据下新增一条可编辑的自定义行,同时提供自定义行无数据显示的表格样式,以及点击编辑按钮切换输入框的功能。
实现步骤
- 引入组件:
import { Table, Input, Button } from 'antd';
- 定义表格数据和列配置:
const columns = [
// 其他列配置...
];
const dataSource = [
// 表格数据...
];
- 创建状态管理:
const [editingRowKey, setEditingRowKey] = useState(null); // 自定义行的编辑状态
const [inputValue, setInputValue] = useState(''); // 自定义行的输入值
- 自定义行渲染函数:
const expandedRowRender = (record) => {
const isEditing = record.key === editingRowKey;
return (
<div>
{isEditing ? (
<Input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onPressEnter={() => saveInput(record)}
onBlur={() => saveInput(record)}
/>
) : (
<Button onClick={() => editInput(record)}>编辑</Button>
)}
</div>
);
};
- 编辑和保存函数:
const editInput = (record) => {
setEditingRowKey(record.key);
setInputValue(record.inputValue || ''); // 初始化输入框值
};
const saveInput = (record) => {
setEditingRowKey(null);
// 这里可以将输入值保存到 dataSource 中或者进行其他操作
};
- 渲染 Table 组件:
return (
<Table
columns={columns}
dataSource={dataSource}
expandedRowRender={expandedRowRender}
/>
);
无数据显示表格样式
当自定义行没有数据时,可以设置 Table 组件的 emptyText 属性来显示自定义的提示信息:
return (
<Table
columns={columns}
dataSource={dataSource}
expandedRowRender={expandedRowRender}
emptyText={<div>暂无数据</div>}
/>
);
代码示例
import React, { useState } from 'react';
import { Table, Input, Button } from 'antd';
const App = () => {
const [dataSource, setDataSource] = useState([
{ key: '1', name: 'John Doe', age: 30 },
{ key: '2', name: 'Jane Doe', age: 25 }
]);
const [editingRowKey, setEditingRowKey] = useState(null);
const [inputValue, setInputValue] = useState('');
const columns = [
{ title: 'Name', dataIndex: 'name', key: 'name' },
{ title: 'Age', dataIndex: 'age', key: 'age' }
];
const expandedRowRender = (record) => {
const isEditing = record.key === editingRowKey;
return (
<div>
{isEditing ? (
<Input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onPressEnter={() => saveInput(record)}
onBlur={() => saveInput(record)}
/>
) : (
<Button onClick={() => editInput(record)}>编辑</Button>
)}
</div>
);
};
const editInput = (record) => {
setEditingRowKey(record.key);
setInputValue(record.inputValue || '');
};
const saveInput = (record) => {
setEditingRowKey(null);
// 更新数据源
const newData = [...dataSource];
const index = newData.findIndex((item) => item.key === record.key);
newData[index].inputValue = inputValue;
setDataSource(newData);
};
return (
<Table
columns={columns}
dataSource={dataSource}
expandedRowRender={expandedRowRender}
emptyText={<div>暂无数据</div>}
/>
);
};
export default App;
总结
通过以上步骤,您可以在 Ant Design 的 Table 组件中实现可编辑的自定义行功能,并根据实际需求进行扩展。同时,您可以根据需要设置无数据显示的表格样式,以提升用户体验。
原文地址: https://www.cveoy.top/t/topic/o2QT 著作权归作者所有。请勿转载和采集!