【问题标题】:Can I initialize the checkbox selection in MUI DataGrid?我可以在 MUI DataGrid 中初始化复选框选择吗?
【发布时间】:2020-09-28 14:50:58
【问题描述】:

在 MUI DataGrid 中,通过 checkboxSelection 属性添加复选框选择并通过 onSelectionChange 监听选择更改非常容易:

<DataGrid
  columns={columns}
  rows={rows}
  pageSize={10}
  checkboxSelection
  onSelectionChange={e => console.log(e.rows)}
/>

但是还有一种方法可以使用一组选中的项目来初始化复选框选择吗?

【问题讨论】:

标签: reactjs material-ui


【解决方案1】:

目前DataGrid 没有办法设置默认selectionModel(类似于defaultSelectionModel 属性),所以为了设置默认选定的行,您需要通过添加@ 来使用controlled mode 987654329@/onSelectionModelChange 并在useState 中传递初始值。它是您希望在开始时选择的行的 ID 数组。

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 }
];

function MyDataGrid() {
  const [selectionModel, setSelectionModel] = React.useState(() =>
    rows.filter((r) => r.age > 40).map((r) => r.id),
  );

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        checkboxSelection
        rows={rows}
        columns={columns}
        selectionModel={selectionModel}
        onSelectionModelChange={setSelectionModel}
      />
    </div>
  );
}

现场演示

【讨论】:

  • 这还能用吗?当我尝试此解决方案时,我收到错误“setRowModels 不是函数”。我正在使用数据网格版本 4.0.0-alpha.13。
  • setRowModels 不是函数
  • @SelmiKarim 抱歉更新晚了,在 alpha 版本中有一些 breaking changes。我又做了演示。
  • @RyanCarville 如果要在组件加载后设置行数据,可以使用useEffect和受控selectionModel。如果您有任何其他问题,请 fork this codesandbox 示例并重现错误。
【解决方案2】:

DataGrid 有一个 selectionModel 属性,该属性接受行 ID 数组。

<DataGrid
  columns={columns}
  rows={rows}
  pageSize={10}
  checkboxSelection
  onSelectionChange={e => console.log(e.rows)}
  selectionModel={[rowId1, rowId2, rowId3]}
/>

【讨论】:

    【解决方案3】:
    import * as React from "react";
    import {
      DataGrid,
      RowData,
      useRows,
      useApiRef,
      GridApi,
    } from "@material-ui/data-grid";
    import { useDemoData } from "@material-ui/x-grid-data-generator";
    
    let i = 0;
    export default function ControlledSelectionGrid() {
      const apiRef = React.useRef(null);
      console.log("apiRef:", apiRef);
      const ObjRef = React.useRef({
          dataRe:{
            columns:[],
            rows:[]
          }
      })
    
      const counterRef = React.useRef({
        renderCount:0
      })
    
        // TODO: https://github.com/mui-org/material-ui-x/issues/246
        const [selection, setSelection] = React.useState([]);
    
      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 },
      ];
    
    
      
    
      //console.log('dataRe out:',ObjRef.current.dataRe)
      
    
      React.useEffect(() => {
        const dataRe = {
          columns,
          rows
        }
        ObjRef.current.dataRe = dataRe
        counterRef.current.renderCount +=1
        console.log('no of render**:',counterRef.current.renderCount)
        console.log('apiRef.current**:',apiRef.current)
        
        //console.log('in useEffect..') 
        const rowModels = apiRef?.current?.getRowModels();
        console.log("rowModels:", rowModels);
        console.log('dataRe',dataRe)
        if (rowModels!=undefined) {
          if(apiRef.current){
            apiRef.current.setRowModels(
              rowModels.map((r) => {
                //console.log("rowModel row:", r);
                r.selected = r.data.age > 40;
                return r;
              })
            );
          }
        }
      },[apiRef.current]);
    
    
      return (
        <div style={{ height: 400, width: "100%" }}>
          <DataGrid
            checkboxSelection
            onSelectionChange={(newSelection) => {
              setSelection(newSelection.rows);
            }}
            components={{
              noRowsOverlay: (params) => {
                //console.log('params in noRowsOverlay:',params)
                if (!apiRef.current) {
                  //console.log('in apiRef current noRowsOverlay')
                  apiRef.current = params.api.current;
                  //console.log('apiRef.current in noRowOverlay:',apiRef.current)
                }
                return <div>No rows</div>;
              },
            }}
            {...ObjRef.current.dataRe}
          />
        </div>
      );
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2021-06-23
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多