react实现表格删除
实现表格删除功能
在React中实现表格删除功能需要结合状态管理和事件处理。以下是一个完整的实现方案:
创建表格组件
定义一个包含表格数据的组件,使用useState管理数据状态:
import React, { useState } from 'react';
function DataTable() {
const [data, setData] = useState([
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
]);
// 删除函数将在这里实现
return (
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{data.map(item => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.age}</td>
<td>
<button onClick={() => handleDelete(item.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
);
}
实现删除功能
添加删除处理函数,通过过滤数组实现删除:
const handleDelete = (id) => {
setData(data.filter(item => item.id !== id));
};
添加确认对话框
为防止误删,可以添加确认对话框:
const handleDelete = (id) => {
if (window.confirm('Are you sure you want to delete this item?')) {
setData(data.filter(item => item.id !== id));
}
};
完整组件代码
import React, { useState } from 'react';
function DataTable() {
const [data, setData] = useState([
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
]);
const handleDelete = (id) => {
if (window.confirm('Are you sure you want to delete this item?')) {
setData(data.filter(item => item.id !== id));
}
};
return (
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{data.map(item => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.age}</td>
<td>
<button onClick={() => handleDelete(item.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
);
}
export default DataTable;
服务器数据删除
如果需要从服务器删除数据,可以使用fetch或axios:
const handleDelete = async (id) => {
if (window.confirm('Are you sure you want to delete this item?')) {
try {
await fetch(`https://api.example.com/items/${id}`, {
method: 'DELETE'
});
setData(data.filter(item => item.id !== id));
} catch (error) {
console.error('Error deleting item:', error);
}
}
};
使用React图标库
为删除按钮添加图标提升用户体验:
import { FaTrash } from 'react-icons/fa';
// 在按钮中使用图标
<button onClick={() => handleDelete(item.id)}>
<FaTrash />
</button>
这种方法提供了完整的表格删除功能实现,包括本地状态管理和服务器交互选项。根据实际需求选择适合的方案。







