如何在 MUI datagrid checkboxSelection 中显示已选择的数据

问题描述 投票:0回答:1

我在 React webapp 中使用 Datagrid,我希望在数据网格上已经选择了一些行,因为它们是之前选择的。

现在用户可以访问服务器 A、C 和 D。 我该如何实现。 这是代码:

<DataGrid
    rows={rows}
    columns={columns}
    autoPageSize
    disableColumnMenu
    paginationModel={{ page: 0, pageSize: 15 }}
    checkboxSelection
    onRowSelectionModelChange={(ids) => {
        const selectedIDs = new Set(ids);
        const selectedRows = rows.filter((row) =>
          selectedIDs.has(row.id),
        );
        setSelectedRows(selectedRows.map((rowdata)=>(rowdata.name)));
      }}
  />

请帮帮我。

提前致谢

reactjs material-ui mui-datagrid
1个回答
0
投票

我花了一些时间来深入研究您的问题并找到了有效的解决方案。

使用

selectionModel
,像这样:

selectedRows
其实应该是你的状态)

import { DataGrid } from '@mui/x-data-grid'

const rows = [
    { id: 1, name: 'Alice', age: 15 },
    { id: 2, name: 'Bob', age: 25 },
    { id: 3, name: 'Charles', age: 35 },
]

const selectedRows = [1, 3] // Select rows with ids 1 and 3.

export default function Test() {
    return (
        <>
            <div style={{ height: 400, width: '100%' }}>
                <DataGrid
                    rows={rows}
                    autoPageSize
                    disableColumnMenu
                    paginationModel={{ page: 0, pageSize: 15 }}
                    checkboxSelection
                    columns={[
                        { field: 'firstName', headerName: 'First name', width: 150 },
                        { field: 'lastName', headerName: 'Last name', width: 150 },
                        { field: 'age', headerName: 'Age', type: 'number', width: 90 },
                    ]}
                    selectionModel={selectedRows}
                />
            </div>
        </>
    )
}

© www.soinside.com 2019 - 2024. All rights reserved.