reactjs - 在 DataGrid 列中单击按钮时如何删除一行?
问题描述
我有一个包含用户的数据表,我想让删除按钮在行上工作,但似乎无法通过反应方式完成。
DataGrid 的使用方式如下:
<DataGrid
rows={users}
columns={columns}
pageSize={5}
checkboxSelection
/>
我有一个带有自定义 renderCell 函数的列,它显示了一些操作按钮。列定义是这样的:
{
field: "actions",
headerName: "",
width: 120,
type: "",
sortable: false,
renderCell: (
params: GridCellParams
): React.ReactElement<any, string | React.JSXElementConstructor<any>> => {
return (
<UserRowActions
userId={params.getValue(params.id, "id")?.toString()!}
/>
);
}
}
params 对象提供了一些属性,但我不知道如何执行以下操作:删除单击按钮的行,该按钮在UserRowActions
组件中定义。
我还想了解是否不能像现在这样使用 MUI DataGrid 组件来执行此操作。
我不知道该怎么做,因为 API 现在看起来对我没有反应。
我用:
"@material-ui/core": "^4.12.1",
"@material-ui/data-grid": "^4.0.0-alpha.30",
"react": "^16.14.0",
解决方案
我专门为数据网格操作按钮制作了一个上下文:
export const DataGridContext = React.createContext<{ deleteUser?: (uid: string) => void }>({});
// ...
const { data: users, isLoading, isError } = useGetUsersQuery();
const [usersRows, setUsersRows] = useState<IUser[]>([]);
useEffect(() => {
if (typeof users !== 'undefined') {
setUsersRows(users);
}
}, [users]);
<DataGridContext.Provider value={{ deleteUser: (uid: string) => {
const newRows = [...usersRows];
const idx = newRows.findIndex(u => u.id === uid);
if (idx > -1) {
newRows.splice(idx, 1);
setUsersRows(newRows);
}
}}}>
<DataGrid
rows={usersRows} // ...
/>
</DataGridContext.Provider>
// In the UserRowActions component:
const dataGrid = useContext(DataGridContext);
// ...
dataGrid.deleteUser!(userId);
推荐阅读
- java - 在java 8中合并具有不同类型和长度的多个流
- vue.js - v-on:鼠标悬停条件 VueJS 1.0.21
- python - 数据帧标题错误 - 没有预期的那么多列
- python - 如何确定嵌套列表理解的外循环和内循环?
- sql - 在 SQL 查询中合并记录集值
- angular - 如何取消订阅嵌套的 observable
- java - 如何在 Okta Java SDK 中发送短信挑战
- php - Laravel 原始 SQL 查询,具有多次出现的命名绑定
- reactjs - 测试按钮是否改变状态,或者组件是否出现(反应)
- iis-7.5 - 是否可以在 Server 2008 R2 Server Pack 1 上的 IIS 7.5.1 应用程序池上安装 .NET 4.5?