问题
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:
Console Log on first row click:
UI After selecting one checkbox (clicking directly on the checkbox of another row):
Console Log after clicking the initial row again:
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
回答1:
Figured this one out with some help from @orestes22 in the official material-table Gitter chat.
Add tableRef to state:
state = {
tableRef: React.createRef(),
}
Then add the tableRef prop to your Material Table
<MaterialTable
tableRef={this.state.tableRef}
/>
Then on the onRowClick
prop/function use tableRef to access dataManager
and onSelectionChange
<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);
}}
/>
来源:https://stackoverflow.com/questions/56264459/how-can-i-use-tableref-onrowselected-to-update-the-ui-via-the-onrowclick-propert