我正在尝试获取刚刚从 mui 数据网格编辑的值。我的用例是我希望能够获取这些值并更新状态/发送更新数据库的请求。
我尝试使用 onEditRowsModelChange 和 onRowEditStop 属性,但 onEditRowsModelChange 更新过于频繁,无法满足我的需求,并且 onRowEditStop 返回以前的值,但不是最近更新的值。这些值也采用需要解析才能获得的形式。
有人有这方面的经验吗?
具有默认编辑模式(单元格编辑模式) 你必须使用
onCellEditCommit
const onCellEditCommit= (cellData) => {
const { id, field, value } = cellData;
...
}
<DataGrid
onCellEditCommit={onCellEditCommit}
...
在行编辑模式下,您可以使用
processRowUpdate
,但请确保将 experimentalFeatures={{ newEditingApi: true }}
与数据网格一起使用
const processRowUpdate = (newRow) => {
const updatedRow = { ...newRow, isNew: false };
...
return updatedRow;
};
<DataGrid
editMode="row"
processRowUpdate={processRowUpdate}
experimentalFeatures={{ newEditingApi: true }}
...
您可以使用OnCellEditCommit
<DataGridPro
rows={rows}
columns={columns}
onCellEditCommit={handleRowEditCommit}
/>
你的handleRowEditCommit函数将如下所示
const handleRowEditCommit = React.useCallback(
(params) => {
const id = params.id;
const key = params.field;
const value = params.value; },
[]
);
您可以使用
apiRef
获取已提交行的详细信息。
我已经按照以下方式处理了这种情况:
const apiRef = useGridApiRef();
const onRowEditCommit = (id, event) => {
let row = apiRef.current.getEditRowsModel();
handleRowEdit(row);
}
希望有帮助。
晚了一点,但是。
您正在寻找 processRowUpdate,它收到两个参数,newRow 和 oldRow。
const handleProcessRowUpdate = (newRow, oldRow) => {
//Here manipulate the rows depending on what you want to do
}
<DataGrid
processRowUpdate={handleProcessRowUpdate}
/>
您可以使用 DataGrid API 文档中提到的
processRowUpdate
属性。
下面,我创建了一个函数来更新通过其索引查找的行,然后更新它。您可以使用它来更新您的数据。
这是CodeSandbox的链接。
const handleProcessRowUpdate = (updatedRow, originalRow) => {
// Find the index of the row that was edited
const rowIndex = rows.findIndex((row) => row.id === updatedRow.id);
// Replace the old row with the updated row
const updatedRows = [...rows];
updatedRows[rowIndex] = updatedRow;
// Update the state with the new rows
setRows(updatedRows);
// Return the updated row to update the internal state of the DataGrid
return updatedRow;
};
return (
<Box sx={{ height: 400, width: "100%" }}>
<DataGrid
rows={rows}
columns={columns}
initialState={{
pagination: {
paginationModel: {
pageSize: 5
}
}
}}
processRowUpdate={handleProcessRowUpdate}
pageSizeOptions={[5]}
checkboxSelection
disableRowSelectionOnClick
/>
</Box>
);
我有一个使用 onEditRowsModelChange 方法的相当丑陋的解决方案。 正如您提到的,它会进行一些去抖和解析:
let timer;
const handleEditRowsModelChange = (model) => {
if(timer) clearTimeout(timer);
timer = setTimeout(() => {
setEditRowsModel(model);
let siteId = Object.keys(model)[0];
let field = siteId ? Object.keys(model[siteId])[0] : null;
let value = field ? model[siteId][field].value : null;
siteId && field && (
sites.forEach(site => {
if (site.id == siteId) {
if (site[field] != value) {
site[field] = value;
sendSiteForEdit(site);
}
};
}
));
}, 1500);
};
您好,您成功了吗?我遇到了同样的问题,需要捕获编辑后的数据并将其通过表单传递到 API。谢谢! :)