首页 > 解决方案 > 如何使用按钮取消选中 MaterialTable(mbrn/material-table) 的所有行?

问题描述

我正在构建一个使用 mbrn/material-table( https://github.com/mbrn/material-table ) 的 reactjs Web 应用程序。该表具有一次检查字段中所有行的功能。但是要取消选择(或取消选中)所有行,您需要单击全选复选框,然后再次单击它以取消选中所有行。我已阅读框架的文档,但无法找到实现一次取消选中所有行的功能一个按钮。

  import MaterialTable from "material-table";

     const table = () => {
    return (
       <MaterialTable
         columns={[
          { title: "ID" },
          { title: "name" },
          { title: "SurName" },
          {
            title: "Birthyear"
          },
          { title: "BirthCity" },
         {
          title: "Sex"
         },
         {
          title: "Type"
         }
        ]}
    data={[
         {
          id: 1,
           name: "a",
          surname: "Baran",
          birthYear: 1987,
          birthCity: 63,
          sex: "Male",
         type: "adult"
         },
       {
        id: 2,
        name: "b",
        surname: "Baran",
        birthYear: 1987,
        birthCity: 34,
        sex: "Female",
        type: "adult",
        parentId: 1
      },
      {
        id: 3,
        name: "c",
        surname: "Baran",
        birthYear: 1987,
        birthCity: 34,
        sex: "Female",
        type: "child",
        parentId: 1
      },
      {
        id: 4,
        name: "d",
        surname: "Baran",
        birthYear: 1987,
        birthCity: 34,
        sex: "Female",
        type: "child",
        parentId: 3
      },
      {
        id: 5,
        name: "e",
        surname: "Baran",
        birthYear: 1987,
        birthCity: 34,
        sex: "Female",
        type: "child"
      },
      {
        id: 6,
        name: "f",
        surname: "Baran",
        birthYear: 1987,
        birthCity: 34,
        sex: "Female",
        type: "child",
        parentId: 5
      }
    ]}
    actions={[
      {
        tooltip: "Remove All Selected Users",
        icon: icons,
        onClick: (evt, data) =>
          alert("You want to delete " + data.length + " rows")
      }
    ]}
    // onSelectionChange={rows =>
    //   // alert("You selected " + rows.length + " rows")
    // }
    options={{
      selection: true
    }}
    parentChildData={(row, rows) => rows.find(a => a.id === 
  row.parentId)}
    title="Search Results"
  />);

我希望在单击按钮时,所有选定的行都应该被取消选中

标签: reactjsmaterial-table

解决方案


由于材料表实际上会改变您的数据,因此您可以使用以下内容:

this.state.data.forEach(d => {if(d.tableData)d.tableData.checked = false});

并将其设置为新状态。这不是最漂亮的,因为状态突变,但这是唯一的方法,因为材料表本身会改变它。


推荐阅读