【问题标题】:Select a row in bootstrap style table when the row is clicked单击行时在引导样式表中选择一行
【发布时间】:2017-12-01 08:37:34
【问题描述】:

点击时如何突出显示表格中的一行?我尝试过使用onClick 函数,但我无法实现。

这是我用来将表格数据映射到td标签的函数。

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

这里我在渲染函数中调用了这个函数。

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

【问题讨论】:

    标签: javascript twitter-bootstrap reactjs


    【解决方案1】:

    您必须为每个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>
      ));
    }
    

    你的handleCellClick函数可以实现如下:

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

    最后你的highlited-cell 类可以根据你的喜好编写:

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

    【讨论】:

    • 感谢您的快速回复。我会试试的。
    • 不客气,您不妨点赞并选择正确答案,谢谢
    猜你喜欢
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    相关资源
    最近更新 更多