gpt4 book ai didi

reactjs - 如何删除 Material-UI DataGrid 中的多个选定行?

转载 作者:行者123 更新时间:2023-12-05 03:37:14 26 4
gpt4 key购买 nike

我想知道如何使用 React 中的复选框从 Material-UI 的 DataGrid 中删除行。我没有在 DataGrid 上找到任何合适的教程来执行此操作,尽管我为 MaterialTable 找到了一个但是不一样。

enter image description here

欢迎任何帮助。

更新

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

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

更新一切正常!谢谢

enter image description here

最佳答案

您可以通过 selectionModel/onSelectionModelChange 跟踪当前选择的 ID Prop ,并在用户单击标题上的 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>
);

Codesandbox Demo

关于reactjs - 如何删除 Material-UI DataGrid 中的多个选定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69384072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com