首页 > 解决方案 > 如何使用 React 更改选定的表格行背景颜色

问题描述

我想在单击时更改表格行背景颜色,并在单击另一行时更改为原来的颜色。

我试过这样的事情:

index.js

state = {
    color: []    
  }



render(){    
 return (
        <Table>
          <thead>
            <tr>
              <th>name</th>
              <th>age</th>
              <th>address</th>
            </tr>
          </thead>
          <tbody className="tableHover">
            {this.props.students.map((item, i) => {
              return (
                <tr key={i} onClick={this.changeColor(i)}>
                  <td>{item.name}</td>
                  <td>{item.age}</td>
                  <td>{item.address}</td>
                </tr>
              );
            })}
          </tbody>
        </Table>
    );

    changeColor = (selectedRow) => e => {
      if (selectedRow){
       this.setState({color: 'blue'})
      }
    }
}

样式.css

.tableHover :hover {
  color: white;
  background-color: blue;
}

提前致谢!

标签: cssreactjs

解决方案


selectedRow您可以在其中维护一个state并根据匹配索引向该行添加一个类名。

className={this.state.selectedRow === i ? "tableSelected" : "" }

下面的完整工作代码

class App extends React.Component {
  state = {
    selectedRow: -1
  };

  render() {
    return (
      <table>
        <thead>
          <tr>
            <th>name</th>
            <th>age</th>
            <th>address</th>
          </tr>
        </thead>
        <tbody className="tableHover">
          {this.props.students.map((item, i) => {
            return (
              <tr key={i} onClick={this.changeColor(i)} className={this.state.selectedRow === i ? "tableSelected" : "" }>
                <td>{item.name}</td>
                <td>{item.age}</td>
                <td>{item.address}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    );
  }

  changeColor = selectedRow => e => {
    if (selectedRow !== undefined) {
      this.setState({ selectedRow  });
    }
  };
}

ReactDOM.render(<App students={[{name: "a"}, {name: "b"}]}/>, document.getElementById("app"));
.tableHover :hover {
  color: white;
  background-color: blue;
}

.tableSelected {
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>


推荐阅读