Man*_*vie 10 reactjs material-ui
我有一个包含多个元素的数据网格,我想检索已检查的数据。我在元素文档中看到有一个受控选择,但我无法让它工作。我将把我当前的代码放在下面,提前谢谢!
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>
);
}
Run Code Online (Sandbox Code Playgroud)
如果您记录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>
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34213 次 |
| 最近记录: |