首页 > 解决方案 > 在 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",

标签: reactjstypescriptreact-hooksmaterial-uimui-datatable

解决方案


我专门为数据网格操作按钮制作了一个上下文:

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);


推荐阅读