我有一个包含多个元素的数据网格,我想检索已检查的数据。 我在元素文档中看到有一个受控选择,但是我无法使其正常工作。 我将当前代码放在下面,谢谢!!
import * as React from 'react';
import { DataGrid } from '@material-ui/data-grid';
const columns = [
{ field: 'id', headerName: 'ID', width: 70 },
{ field: 'firstName', headerName: 'First name', width: 130 },
{ field: 'lastName', headerName: 'Last name', width: 130 },
{
field: 'age',
headerName: 'Age',
type: 'number',
width: 90,
},
{
field: 'fullName',
headerName: 'Full name',
description: 'This column has a value getter and is not sortable.',
sortable: false,
width: 160,
valueGetter: (params) =>
`${params.getValue('firstName') || ''} ${
params.getValue('lastName') || ''
}`,
},
];
const rows = [
{ id: 1, lastName: 'Snow', firstName: 'Jon', age: 35 },
{ id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 42 },
{ id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 45 },
{ id: 4, lastName: 'Stark', firstName: 'Arya', age: 16 },
{ id: 5, lastName: 'Targaryen', firstName: 'Daenerys', age: null },
{ id: 6, lastName: 'Melisandre', firstName: null, age: 150 },
{ id: 7, lastName: 'Clifford', firstName: 'Ferrara', age: 44 },
{ id: 8, lastName: 'Frances', firstName: 'Rossini', age: 36 },
{ id: 9, lastName: 'Roxie', firstName: 'Harvey', age: 65 },
];
export default function App() {
const [select, setSelection] = React.useState([]);
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
pageSize={25}
checkboxSelection
hideFooterPagination
onSelectionChange={(newSelection) => {
setSelection(newSelection.rows);
}}
/>
<h1>{select}</h1>
</div>
);
}
答案 0 :(得分:0)
如果您记录select
状态,则可以看到该状态是根据所选内容设置的。 onSelectionChange
回调newSelection
参数已包含您要查找的内容。
您的代码的主要问题是<h1>{select}</h1>
。尽管select
确实是一个数组,并且数组是有效的React子元素,但是每个数组元素都包含一个对象(例如firstName
,lastName
),因此它不适用于该设置
您可以遍历数组并打印每个单独的数组元素对象属性值。
下面的示例打印出firstName
:
return (
<div style={{ height: 400, width: "100%" }}>
<h1>{select.map((val) => val.firstName)}</h1>
<DataGrid
rows={rows}
columns={columns}
pageSize={25}
checkboxSelection
hideFooterPagination
onSelectionChange={(newSelection) => {
setSelection(newSelection.rows);
}}
/>
</div>
);
答案 1 :(得分:0)
我相信您可以从获取总行数 onRowSelected
开始,或者通过稍微进入 api 从其他事件方法的上下文中开始。这是截至 2020 年 3 月,但我在 API 文档中没有发现任何相关内容:
onRowSelected={(x) => x.api.current.getSelectedRows()}
,在 DataGrid 上 "@material-ui/data-grid": "^4.0.0-alpha.22"
对我有用。在我的情况下,我可以做我需要的一切。
答案 2 :(得分:0)
文档已更新,我更新了此示例:answer from this topic,现在根据文档 selectionModel
包含一个 id
选定行的数组