简体   繁体   English

单击该行时在引导程序样式表中选择一行

[英]Select a row in bootstrap style table when the row is clicked

How to highlight a row from the table when it is clicked? 单击时如何突出显示表格中的行? I have tried using onClick function but I cannot achieve it. 我尝试使用onClick函数,但无法实现。

This is the function I used for mapping the table data to td tag. 这是我用来将表数据映射到td标签的功能。

displayData() {   
       let x;
       if (this.props.data) {
       x = this.props.data.map(item => (
       <tr>
       <td> {item.height} </td>
       </tr>
      ));
    }
    return x;
    }

Here I have called this function inside the render function. 在这里,我在render函数中调用了此函数。

        <Table id="tableId" >
        <thead>
        <tr>
        <th> height </th>
       </tr>
      </thead>
     <tbody> {this.displayData()} </tbody>
     </Table>

You have to provide an key to every td , then a className property that will change depending on the id existing currently in the state and of course an onClick event handler that will fill in the state with the clicked id, therefore this block: 您必须为每个td提供一个key ,然后是一个className属性,该属性将根据state当前存在的ID发生变化,当然还有一个onClick事件处理程序,该事件处理程序将使用单击的ID来填充状态,因此此代码块:

  if (this.props.data) {
   x = this.props.data.map((item,key) => (
   <tr>
   <td
     key={key}
     onClick={this.handleCellClick(key)}
     className={`${this.state.checkedId===key? 'highlighted-cell': ''}`}
      > {item.height} </td>
   </tr>
  ));
}

and your handleCellClick function can be implemented as follows: 并且您的handleCellClick函数可以实现如下:

handleCellClick = (key) => (event) => {

if(this.state.checkedId===key){
   this.setState({
      checkedId: '',
     });
   }else{
   this.setState({
      checkedId: key,
     });
   }
  }

finally your highlited-cell class can be written as per your preferences: 最后,您的highlited-cell类可以按照您的喜好编写:

.highlighted-cell {
   background-color: blue;
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM