要在Material Table中验证删除,可以使用onRowDelete属性来处理删除操作,并在删除之前进行验证。
以下是一个示例代码:
import React from 'react';
import MaterialTable from 'material-table';
import { confirmAlert } from 'react-confirm-alert';
import 'react-confirm-alert/src/react-confirm-alert.css';
export default function App() {
const data = [
{ id: 1, name: 'John Doe', age: 25 },
{ id: 2, name: 'Jane Smith', age: 30 },
{ id: 3, name: 'Bob Johnson', age: 35 },
];
const columns = [
{ title: 'ID', field: 'id' },
{ title: 'Name', field: 'name' },
{ title: 'Age', field: 'age' },
];
const handleDelete = (oldData) => {
confirmAlert({
title: 'Confirm Delete',
message: 'Are you sure you want to delete this row?',
buttons: [
{
label: 'Yes',
onClick: () => {
// Perform delete operation here
const newData = [...data];
const index = data.indexOf(oldData);
newData.splice(index, 1);
setData(newData);
},
},
{
label: 'No',
onClick: () => {},
},
],
});
};
const [tableData, setData] = React.useState(data);
return (
new Promise((resolve, reject) => {
handleDelete(oldData);
resolve();
}),
}}
/>
);
}
在上面的代码中,我们使用了react-confirm-alert
库来显示一个确认对话框来验证删除操作。当用户点击“Yes”按钮时,我们执行实际的删除操作,并更新表格的数据。当用户点击“No”按钮时,我们不执行任何操作。
注意:为了运行上述代码,您需要安装react-confirm-alert
和material-table
库,并在代码中进行适当的导入。