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

♀尐吖头ヾ 提交于 2020-12-08 06:26:14

问题


I have the following code for retrieving data of the clicked row:

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

How can I change the background color of the clicked row? Or what is the best way to highlight the clicked row?


回答1:


Please see here for an answer: Select row on click react-table

Here is my code:

First of all you need a state:

  this.state = {
    selected: -1
  };

-1 is important because otherwise the row with the index 0 will be highlighted without clicking on it.

And getTdProps looks like this:

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'
            },
        }
    }
}}


来源:https://stackoverflow.com/questions/49631293/react-table-how-to-change-the-background-color-of-a-row-if-it-is-clicked-selec

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!