【问题标题】:How to change the cell background color for child cells如何更改子单元格的单元格背景颜色
【发布时间】:2020-04-28 13:18:34
【问题描述】:

我在这个 UI 中使用 material-table

我正在尝试仅在 onTreeExpandChange 为 true 时自定义特定单元格的样式。

所以基本上我只想为单元格 2 和 3 设置不同的背景颜色。我附上了一个屏幕截图以获得理想的结果。这将帮助我仅识别子列标题。

一些代码示例:

                  {
                        title: 'WEST',
                         field: 'west',
                        cellStyle: { textAlign: 'center' },
                        headerStyle: { backgroundColor: '#006EB8' }
                    },
                ]}
                data={[
                    { id: 1, group_name: '1', northeast: 'Baran', central: 'ddd', west: '3' },
                    { id: 2, parentId: 1, group_name: '2', northeast: 'Baran', central: 'ddd', west: '3' },
                    { id: 3, parentId: 1, group_name: '3', northeast: 'Baran', central: 'ddd', west: '3' },
                    { id: 4, group_name: '4', northeast: 'Baran', central: 'ddd', west: '3' },
                    { id: 5, group_name: '5', northeast: 'Baran', central: 'ddd', west: '3' },
                    { id: 6, group_name: '6', northeast: 'Baran', central: 'ddd', west: '3' },
                ]}
                onTreeExpandChange={(row, rows) => {
                    if (rows) {
                        // How to changne the backgroundColor of cell 2 & 3 ?????
                    }
                }
                }
                parentChildData={(row, rows) => rows.find(a => a.id === row.parentId)}
                options={{
                    search: false,
                    sorting: true,
                    exportButton: true,
                    paging: false,

知道如何做到这一点吗?

谢谢

【问题讨论】:

  • 您是否尝试过使用console.log() 查看rowrows 中的数据?如果 row 具有 .style 属性,则您将设置为 row.style.backgroundColor="#FF0;"
  • 是的,我做到了。 Row 实际上包含 Object 数据,因此没有样式。

标签: css reactjs material-ui material-table


【解决方案1】:

行样式似乎只能在 React 组件的 options 属性中使用,因此您必须在每次向下钻取时保持状态,将行 ID 添加到状态。

类似这样的:

options={{
  rowStyle: rowData => ({
    backgroundColor: (this.state.expandedRow && this.state.expandedRow.indexOf(rowData.id) != -1) ? '#FF0' : '#FFF'
  })
}}

并且您在您的状态中保留了一个 this.state.expandedRow 数组,您将行 ID 放在 onTreeExpandChange 事件中。

【讨论】:

  • 感谢 Niloct 的帮助。我很感激。我实际上使用 getElementsByTagName 解决了这个问题,并通过 onTreeExpandChange 中的 setAttribute 更改样式。
  • 好吧,如果你想听听我的意见,我建议你不要使用变通方法:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
  • 2013-04-12
  • 2021-10-31
  • 2011-04-03
  • 2013-06-15
  • 2016-05-27
相关资源
最近更新 更多