React.js:如何在加载材料表时使所有行复选框都为true,并在单击时取消选择,反之亦然?

时间:2020-10-28 10:56:11

标签: javascript reactjs material-ui material-table

我在我的项目中使用反应物料表,我想在加载页面时默认选择全选。如何实现?当我取消选中任何复选框时,它也应该被取消选中。 我尝试使用

selectionProps: rowData => ({
    checked: true
}),

但是它已选中所有复选框,并且不能取消选择。

function BasicSelection() {
  return (
    <MaterialTable
      title="Basic Selection Preview"
      columns={[
        { title: 'Name', field: 'name' },
        { title: 'Surname', field: 'surname' },
        { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
        {
          title: 'Birth Place',
          field: 'birthCity',
          lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
        },
      ]}
      data={[
        { name: 'a', surname: 'b', birthYear: c, birthCity: d },
        { name: 'e', surname: 'f', birthYear: g, birthCity: h },
      ]}        
      options={{
        selection: true
      }}
    />
  )
}

1 个答案:

答案 0 :(得分:0)

您需要为每个行数据添加 tableData:{已选中:true}

function BasicSelection() {
  return (
    <MaterialTable
      title="Basic Selection Preview"
      columns={[
        { title: 'Name', field: 'name' },
        { title: 'Surname', field: 'surname' },
        { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
        {
          title: 'Birth Place',
          field: 'birthCity',
          lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
        },
      ]}
      data={[
        {
            tableData: { checked: true },
            name: 'Mehmet',
            surname: 'Baran',
            birthYear: 1987,
            birthCity: 63 },
        {
           tableData: { checked: true },
           checked: true,
           name: 'Zerya Betül',
           surname: 'Baran', 
           birthYear: 2017, 
           birthCity: 34 },
      ]}      
      options={{
        selection: true
      }}
    />
  )
}

这完全按照您想要的方式工作。