2

I've written an onRowClick function to change the rows tableData.checked value when the row is click as seen in the answer here #300

I can see the checked state updating in a console log but the checkbox itself does not change visibly until I actually click another rows checkbox. It will then show all the checkboxes that had their tableData.checked values updated. I'd like to be able to have the checkbox actually display this change to the user onRowClick.

Here is my current code:

<MaterialTable
          onRowClick={(event, rowData) => {
            console.log(event.target, rowData);
            console.log(
              "Row Selection State Before: " + rowData.tableData.checked
            );
            rowData.tableData.checked = !rowData.tableData.checked;
            console.log(
              "Row Section State After: " + rowData.tableData.checked
            );
          }}
         options={{ selection: true}}
/>

This is the state of the UI on my first row click:

Screen Shot 2019-04-04 at 2 32 27 PM

Console Log on first row click:

Screen Shot 2019-04-04 at 2 32 46 PM

UI After selecting one checkbox (clicking directly on the checkbox of another row):

Screen Shot 2019-04-04 at 2 34 32 PM

Console Log after clicking the initial row again:

Screen Shot 2019-04-04 at 2 35 23 PM

Is there any way to make sure the UI updates for the MaterialTable component without resetting anything when the checked state is updated programmatically?

I've also gotten tableRef.onRowSelected working properly but the UI still doesn't re-render with the rows checkbox selected.

Here is the codesandbox with the fix I've attempted

4

1 回答 1

4

在官方材料表 Gitter 聊天中,在 @orestes22 的帮助下想出了这一点。

将 tableRef 添加到状态:

state = {
  tableRef: React.createRef(),
}

然后将 tableRef 道具添加到您的材料表

<MaterialTable
    tableRef={this.state.tableRef}
    />

然后在onRowClickprop/function 上使用 tableRef 访问dataManageronSelectionChange

<MaterialTable
    tableRef={this.state.tableRef}
    onRowClick={(event, rowData) => {
        // Update the clicked rows checked state
        rowData.tableData.checked = !rowData.tableData.checked;

        // pass dataManager the current rows checked state and path/ID, the path/ID needs to be an array, ex: [1]
        this.state.tableRef.current.dataManager.changeRowSelected(
           rowData.tableData.checked,
           [rowData.tableData.id]
        );

        // call the onSelectionChange and pass it the row selected to ensure it updates your selection properly for any custom onSelectionChange functions.
        this.state.tableRef.current.onSelectionChange(rowData);
    }}
    />
于 2019-05-23T20:03:09.103 回答