【问题标题】:How to delete a row when a button is clicked inside a DataGrid column?在 DataGrid 列中单击按钮时如何删除一行?
【发布时间】:2021-09-23 10:15:16
【问题描述】:

我有一个包含用户的数据表,我想在行上设置一个删除按钮,但似乎无法通过反应方式完成。

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",

【问题讨论】:

    标签: reactjs typescript react-hooks material-ui mui-datatable


    【解决方案1】:

    我专门为数据网格操作按钮做了一个context

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

    【讨论】:

      猜你喜欢
      • 2011-04-29
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多