React-Table:如果用鼠标单击(选中)一行,如何更改该行的背景颜色?

React-Table: How to change the background color of a row if it is clicked (selected) with the mouse?

我有以下代码来检索点击行的数据:

    <ReactTable
      getTdProps={(state, rowInfo, column, instance) => {
        return {
          onClick: (e, handleOriginal) => {
            if (typeof rowInfo !== "undefined") this.rowClick(rowInfo.row.RecipeName);
            if (handleOriginal) {
              handleOriginal()
            }
          }
        }
      }}

如何更改点击行的背景颜色?或者突出显示单击的行的最佳方式是什么?

请在这里查看答案:

这是我的代码:

首先你需要一个状态:

  this.state = {
    selected: -1
  };

-1 很重要,否则索引为 0 的行将在不单击的情况下突出显示。

getTdProps 看起来像这样:

getTrProps={(state, rowInfo, column, instance) => {
    if (typeof rowInfo !== "undefined") {
        return {
            onClick: (e, handleOriginal) => {
                this.setState({
                selected: rowInfo.index
                });
                if (handleOriginal) {
                handleOriginal()
                }
            },
            style: {
                background: rowInfo.index === this.state.selected ? '#00afec' : 'white',
                color: rowInfo.index === this.state.selected ? 'white' : 'black'
            },
        }
    }
    else {
        return {
            onClick: (e, handleOriginal) => {
                if (handleOriginal) {
                handleOriginal()
                }
            },
            style: {
                background: 'white',
                color: 'black'
            },
        }
    }
}}