在数据网格(Data Grid)视图中,禁用行选择可以通过设置选择模式(Selection Mode)实现。以下是一个简单的示例,展示了如何在数据网格视图中禁用行选择:
import React, { useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';
const columns = [
{ field: 'id', headerName: 'ID', width: 100 },
{ field: 'name', headerName: 'Name', width: 150 },
{ field: 'age', headerName: 'Age', type: 'number', width: 100 },
];
const rows = [
{ id: 1, name: 'Alice', age: 35 },
{ id: 2, name: 'Bob', age: 42 },
{ id: 3, name: 'Charlie', age: 28 },
];
export default function DataGridDemo() {
const [selectionModel, setSelectionModel] = useState([]);
return (
<div style={{ height: 300, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
disableSelectionOnClick
selectionModel={selectionModel}
onSelectionModelChange={(newSelection) => {
setSelectionModel(newSelection);
}}
/>
</div>
);
}
在上面的示例中,我们使用了 disableSelectionOnClick
属性来禁用行选择。此外,我们还使用了 selectionModel
和 onSelectionModelChange
属性来控制选择模式。
如果您希望在某些特定的行上禁用选择,可以使用 getRowClassName
属性来为这些行添加自定义的 CSS 类名,然后在 CSS 中使用 pointer-events: none
属性来禁用它们的点击事件。例如:
import React, { useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';
const columns = [
{ field: 'id', headerName: 'ID', width: 100 },
{ field: 'name', headerName: 'Name', width: 150 },
{ field: 'age', headerName: 'Age', type: 'number', width: 100 },
];
const rows = [
{ id: 1, name: 'Alice', age: 35 },
{ id: 2, name: 'Bob', age: 42 },
{ id: 3, name: 'Charlie', age: 28 },
];
export default function DataGridDemo() {
const [selectionModel, setSelectionModel] = useState([]);
return (
<div style={{ height: 300, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
disableSelectionOnClick
selectionModel={selectionModel}
onSelectionModelChange={(newSelection) => {
setSelectionModel(newSelection);
}}
getRowClassName={(params) => {
return params.row.id === 2 ? 'disable-selection' : '';
}}
classes={{
'disable-selection': 'disable-selection',
}}
/>
</div>
);
}
在上面的示例中,我们使用了 getRowClassName
属性来为第二行添加自定义的 CSS 类名 disable-selection
,然后在 CSS 中使用 pointer-events: none
属性来禁用它的点击事件。这样,用户就无法选择这一行了。
领取专属 10元无门槛券
手把手带您无忧上云