如何使用 tableRef.onRowSelected 通过 onRowClick 属性 更新 UI?

How can I use tableRef.onRowSelected to update the UI via the onRowClick property?

我编写了一个 onRowClick 函数来在单击行时更改行 tableData.checked 值,如此处的答案所示 #300

我可以在控制台日志中看到选中的状态正在更新,但是在我实际单击另一行复选框之前,复选框本身不会发生明显变化。然后它将显示所有更新了 tableData.checked 值的复选框。我希望能够让复选框实际向用户 onRowClick 显示此更改。

这是我当前的代码:

<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}}
/>

这是我第一行点击UI的状态:

控制台登录第一行点击:

UI选中一个复选框后(直接点击另一行的复选框):

再次单击初始行后的控制台日志:

checked 状态以编程方式更新时,是否有任何方法可以确保 UI 更新 MaterialTable 组件而不重置任何内容?

我也已经 tableRef.onRowSelected 正常工作了,但是 UI 仍然没有在选中行复选框的情况下重新呈现。

Here is the codesandbox with the fix I've attempted

在官方 material-table Gitter 聊天中@orestes22 的帮助下解决了这个问题。

将 tableRef 添加到状态:

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

然后将 tableRef 道具添加到您的 Material Table

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

然后在 onRowClick prop/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);
    }}
    />