首页 > 解决方案 > 材料ui datagrid复选框行选择不起作用

问题描述

 <DataGrid
                className="list"
                pagingation
                rows={registeredClasses} 
                columns={this.getColumns()}
                pageSize={10}
                rowLength={10}
                autoHeight
                // sortModel={sortModel}
                components={{
                  pagination:CustomPagination
                }}
                checkboxSelection
                onSelectionChange={(newSelection) =>{
                  console.log(newSelection)
                }}
                
               
              />

也尝试使用 onSelectionModelChange,仅当我单击行时才会发生选择,如果我单击复选框则不会发生

标签: reactjsreact-material

解决方案


v4.0.0-alpha.34 +

Version 中包含了重大更改v4.0.0-alpha.34onRowSelected已被删除,onSelectionModelChange现在返回一个包含所选行索引的数组。您可以通过以下方式直接更改选择模型onSelectionModelChange

Material UI 文档中的示例:

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

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

  const [selectionModel, setSelectionModel] = React.useState([])

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

更新代码沙盒演示

Material UI Docs - 受控选择

GitHub 上的 Material UI DataTable 更改日志

版本 4.0.0-alpha.21:

代替

onSelectionChange={(newSelection) => {
    console.log(newSelection)
}}

试试onRowSelected,像这样:

onRowSelected={(GridRowSelectedParams) => {
    console.log(GridRowSelectedParams);
}}

如果你想跟踪所有行的选择状态,你应该使用这个:

onSelectionModelChange={(GridSelectionModelChangeParams) => {
    // This will return {selections: [selected row indexes]}
    console.log(GridSelectionModelChangeParams);
    if (Array.isArray(GridSelectionModelChangeParams.selectionModel)) {
        // Iterate the selection indexes:
        GridSelectionModelChangeParams.selectionModel.forEach(
            // Get the row data:
            (selection_index) => console.log(rows[selection_index])
        );
    }
}}

我设置了一个带有工作演示的代码沙箱供您试用


推荐阅读