【问题标题】:React rendering another table row with click dynamic通过点击动态反应渲染另一个表格行
【发布时间】:2018-09-24 10:59:19
【问题描述】:

Hey Stack OverFlow 社区 我正在处理一个 React 项目,我在其中映射一组表行。在每个表格行中,我都有一个附加行,其中包含有关每个个人行数据的更多信息。我的问题是,当我单击按钮以呈现该表的附加信息时,它会呈现所有行的所有附加信息。

我了解我的逻辑是通过一种方式实现的,即每一个额外的行都会在点击时显示。我能做些什么来解决这个问题?

https://codesandbox.io/s/rj8o4r493n

showDrawyer = () => {
    let {showDrawyer} = this.state
    this.setState({
        showDrawyer: !showDrawyer
    })
}

renderTableCellData = () => {
    let { tableData } = this.props;
    return tableData.map((data, index) => {
      return (
        <Table.Body>
        <Table.Row style={{ height: 75 }}>
             <Table.Cell onClick={this.showDrawyer}>{data.name}</Table.Cell>
             <Table.Cell>{data.number}</Table.Cell>
             <Table.Cell>{data.date}</Table.Cell>
             <Table.Cell>{data.uid}</Table.Cell>
        </Table.Row>
            <Table.Row style={{display: this.state.showDrawyer ? '' : 'none' }}>
          <Table.Cell>Hidden Row data</Table.Cell>
          </Table.Row>
        </Table.Body>
      )
    })
}

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:
    state={
        shownDrawerIndex:null
    }    
    
    showDrawyer = (index) => {
            this.setState({
               shownDrawerIndex:index
            })
        }
    
        renderTableCellData = () => {
            let { tableData } = this.props;
            return tableData.map((data, index) => {
              return (
                <Table.Body>
                <Table.Row style={{ height: 75 }}>
                     <Table.Cell onClick={()=>this.showDrawyer(index)}>{data.name}</Table.Cell>
                     <Table.Cell>{data.number}</Table.Cell>
                     <Table.Cell>{data.date}</Table.Cell>
                     <Table.Cell>{data.uid}</Table.Cell>
                </Table.Row>
                    <Table.Row style={{display: this.state.shownDrawerIndex == index ? '' : 'none' }}>
                  <Table.Cell>Hidden Row data</Table.Cell>
                  </Table.Row>
                </Table.Body>
              )
            })
        }
    

    您必须在点击时传递行的索引。这会将状态设置为该索引。 React 将在设置状态下重新渲染组件。在执行此操作时,它将检查状态中的抽屉索引值。 根据那个状态值,它会显示和隐藏抽屉

    【讨论】:

      【解决方案2】:

      解决方案取决于您是希望 (1) 显示多行的附加详细信息,还是 (2) 单击某一行后,仅显示该行的附加详细信息,而对于之前单击的行隐藏.

      对于 (1) 向 tableData 数组添加一个 showDrawyer 字段,该字段将被测试以确定是否显示此元素的附加信息。
      OnClick 应将单击的数组元素作为参数获取,并应切换此元素的 showDrawyer 值。

      对于 (2) - 决定显示哪一行的附加详细信息的状态变量将是一个索引,而不是一个切换。将检查此索引以显示其他详细信息。

      【讨论】:

        猜你喜欢
        • 2017-08-25
        • 1970-01-01
        • 2019-01-17
        • 1970-01-01
        • 1970-01-01
        • 2020-01-03
        • 1970-01-01
        • 1970-01-01
        • 2022-12-13
        相关资源
        最近更新 更多