material-table 如何 select 一行在 selection 上改变背景颜色

material-table How do I select a row changing the background color upon selection

使用 material-table 库。 我想复制此示例中显示的行为。

https://codesandbox.io/s/table-hover-colors-zw9nt

https://www.npmjs.com/package/material-table https://material-table.com/#/

我在考虑使用 onRowClick={}

逻辑是

onRowClick =>

  1. 在组件状态中设置值,将单击的行背景呈现为不同的颜色
  2. 将所有其他行的背景设置为原始颜色

我可以使用基于状态中保存的值的条件渲染来更改背景。虽然这会更改所有行的背景。

options={
   rowStyle:{backgroundColor: this.state.selected ? '#fff' : this.state.c}
}

我当前的工作示例在这里 https://codesandbox.io/s/peaceful-haibt-2nefw

感谢您的帮助

包的 documentation 提供了一个示例,说明如何使用 options 道具完成此操作。

我分叉了你的沙箱 here

你还需要通过 selectedRowId 否则一切都是蓝色的。此外,rowStyle 选项接受回调,您可以像这样调用它:

rowStyle: rowData => ({
backgroundColor: this.state.selected && rowData.tableData.id === this.state.selectedRowId 
?   this.state.c
    : "#fff" 
})

您的 onRowClick 还需要一些工作(select/unselect 条件不正确)。 https://codesandbox.io/embed/select-one-row-160vm