如何使用 Data Grid Mui 选择或取消选择表中的行

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

如何在 @mui/x-data-grid 中使用 onclick 来选择和取消选择一行而不使用 checkboxSelection 属性, 我正在尝试在 Mui 中实现行的选择或取消选择 下面是表格组件文件

import * as React from "react";
import { v1 } from "uuid";
import {
  DataGrid,
  GridToolbarContainer,
  GridToolbarExport
} from "@mui/x-data-grid";

//css
import css from "./index.module.css";

export default function Table(props) {
  const { tableHeader, data } = props;


  data.forEach((element) => {
    element["id"] = v1();
  });

  function CustomToolbar() {
    return (
      <GridToolbarContainer>
        <GridToolbarExport className={`${css.btn}`} />
      </GridToolbarContainer>
    );
  }

  return (
    <div style={{ height: 350, width: "100%" }}>
      <DataGrid
        className={`${css.root}`}
        rows={data}
        columns={tableHeader}
        pageSize={10}
        rowHeight={30}
        autoPageSize={true}
        disableColumnMenu={true}
        components={{
          Toolbar: CustomToolbar,
        }}
      />
    </div>
  );
}

javascript reactjs material-ui datagrid
2个回答
0
投票

根据MUI文档,您将需要通过包中的

useDemoData
钩子
@mui/x-data-grid-generator

import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';

export default function SingleRowSelectionGrid() {
  const { data } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 10,
    maxColumns: 6,
  });

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid {...data} />
    </div>
  );
}

如果您想取消选择一行,只需按住Ctrl并单击它即可。


0
投票

阅读您对 @underflow 的答案的评论后,我假设您正在以编程方式查找选择/取消选择行,而无需使用鼠标或键盘手动单击行。

对于

@mui/x-data-grid": "^7.15.0",

   const [selectedRows, setSelectedRows] = useState([]);

并将它们与道具

rowSelectionModel
onRowSelectionModelChange
一起使用。

   <DataGrid
    ...
    rowSelectionModel={selectedRows}
    onRowSelectionModelChange={setSelectedRows}
   />

现在您可以使用将回调传递给

onRowSelectionModelChange
,它可以使用您自己的逻辑设置selectedRows,或者直接使用其他方法简单处理它。

例如:

清除选择:

const clearRowSelection = () => {
  setSelectedRows([])
}

选择偶数行:

const selectEvenRows = () => {
  const evenRows = rows.filter((_,index)=> index%2 === 0).map(i=>i.id)
  setSelectedRows(evenRows)
}

取消选择偶数行:

const deselectEvenRows = () => {
  const evenRows = selectedRows.filter((_,index)=>i%2===0)
  setSelectedRows(evenRows)
}

在单击按钮上使用它们来测试或在条件下使用它们来选择/取消选择行。

 <Button onClick={clearRowSelection} > Clear Selections </Button>
 <Button onClick={deselectAllRows} > Deselect even rows </Button>
 <Button onClick={deselectAllRows} > Select even rows </Button>

同样,您可以拥有自己的逻辑来以编程方式选择/取消选择行。

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