【问题标题】:How to delete multiple selected rows in Material-UI DataGrid?如何删除 Material-UI DataGrid 中的多个选定行?
【发布时间】:2021-09-29 22:40:55
【问题描述】:

我想知道如何使用 React 中的复选框从 Material-UI 中删除 DataGrid 中的行。我在DataGrid 上找不到任何合适的教程,虽然我找到了MaterialTable 的教程,但不一样。

欢迎任何帮助。

更新

我在适配解决方案后的完整代码:

import React, { useState, useEffect, Fragment } from 'react'
import {db} from './firebase';
import { useHistory, useLocation } from 'react-router-dom';
import "./ListadoEstudiantes.css"
import * as locales from '@mui/material/locale';
import { DataGrid, 
  GridRowsProp, GridColDef,
  GridToolbarContainer, GridToolbarColumnsButton, GridToolbarFilterButton, GridToolbarExport, GridToolbarDensitySelector} from '@mui/x-data-grid';
import { Button, Container } from "@material-ui/core";
import { IconButton} from '@mui/material';
import PersonAddIcon from '@mui/icons-material/PersonAddSharp';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
import { Box } from '@mui/system';

function ListadoEstudiantes({user}) {

  const history = useHistory("");
  const crearEstudiante = () => {
    history.push("/Crear_Estudiante");
  };

 const [estudiantesData, setEstudiantesData] = useState([])

 const parseData = {
  pathname: '/Crear_Pedidos',
  data: estudiantesData
}

const realizarPedidos = () => {
  if(estudiantesData == 0)
  {
    window.alert("Seleccione al menos un estudiante")
  }
  else {
    history.push(estudiantesData);
  }
};

 function CustomToolbar() {
  return (
    <GridToolbarContainer>
      <GridToolbarFilterButton />
      <GridToolbarDensitySelector />
    </GridToolbarContainer>
  );
}


const [estudiantes, setEstudiantes] = useState([]);
  const [selectionModel, setSelectionModel] = useState([]);
  const columns = [
    { field: 'id', headerName: 'ID', width: 100 },

  {field: 'nombre', headerName: 'Nombre', width: 200},

  {field: 'colegio', headerName: 'Colegio', width: 250},

  {field: 'grado', headerName: 'Grado', width: 150},
    {
      field: "delete",
      width: 75,
      sortable: false,
      disableColumnMenu: true,
      renderHeader: () => {
        return (
          <IconButton
            onClick={() => {
              const selectedIDs = new Set(selectionModel);
              setEstudiantes((r) => r.filter((x) => !selectedIDs.has(x.id)));
              
            }}
          >
            <DeleteOutlinedIcon />
          </IconButton>
        );
      }
    }
  ];

 const estudiantesRef = db.collection("usuarios").doc(user.uid).collection("estudiantes")
 useEffect(() => {
  estudiantesRef.onSnapshot(snapshot => {
    const tempData = [];
    snapshot.forEach((doc) => {
      const data = doc.data();
      tempData.push(data);
    });
    setEstudiantes(tempData);
  })
 }, []);

    return (
      <Container fixed>
      <Box mb={5} pt={2} sx={{textAlign:'center'}}>
      <Button
      startIcon = {<PersonAddIcon />} 
      variant = "contained" 
      color = "primary" 
      size = "medium" 
      onClick={crearEstudiante} >
      Crear Estudiantes
      </Button>
      <Box pl={25} pt={2} sx={{height: '390px', width: "850px", textAlign:'center'}}>
      <DataGrid
        rows={estudiantes}
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}

        components={{
          Toolbar: CustomToolbar,
        }}

        checkboxSelection
        //Store Data from the row in another variable
        onSelectionModelChange = {(id) => {
          setSelectionModel(id);
          const selectedIDs = new Set(id);
          const selectedRowData = estudiantes.filter((row) =>
            selectedIDs.has(row.id)
          );
          setEstudiantesData(selectedRowData)
          console.log(estudiantesData);
        }
      }
        {...estudiantes}
        
      />
      </Box></Box></Container>
    )
}

export default ListadoEstudiantes

更新 一切正常!谢谢

【问题讨论】:

    标签: reactjs datagrid material-ui


    【解决方案1】:

    您可以通过selectionModel/onSelectionModelChange 属性跟踪当前选择的ID,并在用户单击标题上的IconButton 时执行必要的操作。因为renderHeader 回调不提供选择状态,所以我必须通过将columns 定义放在函数体中来使用闭包,这样我就可以在回调中引用selectionModel

    const [rows, setRows] = React.useState(_rows);
    const [selectionModel, setSelectionModel] = React.useState([]);
    const columns: GridColDef[] = [
      { field: "col1", headerName: "Column 1", width: 150 },
      { field: "col2", headerName: "Column 2", width: 150 },
      {
        field: "delete",
        width: 75,
        sortable: false,
        disableColumnMenu: true,
        renderHeader: () => {
          return (
            <IconButton
              onClick={() => {
                const selectedIDs = new Set(selectionModel);
                // you can call an API to delete the selected IDs
                // and get the latest results after the deletion
                // then call setRows() to update the data locally here
                setRows((r) => r.filter((x) => !selectedIDs.has(x.id)));
              }}
            >
              <DeleteIcon />
            </IconButton>
          );
        }
      }
    ];
    
    return (
      <div style={{ height: 400, width: "100%" }}>
        <DataGrid
          rows={rows}
          columns={columns}
          checkboxSelection
          onSelectionModelChange={(ids) => {
            setSelectionModel(ids);
          }}
        />
      </div>
    );
    

    【讨论】:

    • 嗯,我收到一个错误,告诉我有关唯一 ID 的信息,但我确实有唯一 ID...
    • @ReactPotato 您正在传递带有useState() 中的一个元素的数组。将useState([estudiantes]) 更改为useState(estudiantes)
    • @ReactPotato 你可以在回调中调用多个函数:`onSelectionModelChange={(e) => { func1();函数2(); }}
    • @ReactPotato 如果你不使用打字稿,只需删除类型
    • @ReactPotato 将 setEstudiantesData(estudiantesData) 更改为 setEstudiantesData(selectedRowData)selectedRowData 是删除后的新行。问题是您再次设置为当前状态,因此没有任何更新。
    猜你喜欢
    • 2021-01-21
    • 1970-01-01
    • 2021-02-16
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多