_.each 循环渲染带按钮的表格行。影响所有行的 OnClick 函数?

_.each loop render tablerows with button. OnClick function affecting all rows?

我正在尝试呈现一个 table,它将显示产品详细信息并在每行的最后一列有一个购买按钮。目前的问题是,当我点击购买按钮时,table 中的所有产品都被购买了。有什么想法吗?

var TableRows = []

_.each(this.state.productids, (value, index) => {
  TableRows.push(
    <TableRow>
      <TableRowColumn>{this.web3.toDecimal(this.state.productids[index])}</TableRowColumn>
      <TableRowColumn>{this.web3.toUtf8(this.state.names[index])}</TableRowColumn>
      <TableRowColumn>{this.web3.toUtf8(this.state.descriptions[index])}</TableRowColumn>
      <TableRowColumn>{(this.web3.toDecimal(this.state.prices[index])) }</TableRowColumn>
      <TableRowColumn>{this.state.owners[index]}</TableRowColumn>
      <RaisedButton label='Buy' onClick={this.state.productContract.buyProduct.sendTransaction(this.state.productids[index], { from: this.web3.eth.accounts[1], value:this.state.prices[index], gas:2000000 })} primary />
    </TableRow>
  )

我做了两件事:

  1. 我使用 _.map() 函数而不是 _.each() 函数,因为它更快并且遵循 React 不变性模式。
  2. 您缺少环绕 <RaisedButton> 元素的 <TableRowColumn> 元素,这就是按钮将 (click) 应用到整行而不是仅应用 [=14= 的原因]元素。

// Your code:
/* var TableRows = []

_.each(this.state.productids, (value, index) => {
  TableRows.push(
    <TableRow>
      <TableRowColumn>{this.web3.toDecimal(this.state.productids[index])}</TableRowColumn>
      <TableRowColumn>{this.web3.toUtf8(this.state.names[index])}</TableRowColumn>
      <TableRowColumn>{this.web3.toUtf8(this.state.descriptions[index])}</TableRowColumn>
      <TableRowColumn>{(this.web3.toDecimal(this.state.prices[index])) }</TableRowColumn>
      <TableRowColumn>{this.state.owners[index]}</TableRowColumn>
      <RaisedButton label='Buy' onClick={this.state.productContract.buyProduct.sendTransaction(this.state.productids[index], { from: this.web3.eth.accounts[1], value:this.state.prices[index], gas:2000000 })} primary />
    </TableRow>
  )*/
  
const TableRows = _.map(this.state.productids, (value, index) => {
  return <TableRow>
    <TableRowColumn>{this.web3.toDecimal(this.state.productids[index])}</TableRowColumn>
      <TableRowColumn>{this.web3.toUtf8(this.state.names[index])}</TableRowColumn>
      <TableRowColumn>{this.web3.toUtf8(this.state.descriptions[index])}</TableRowColumn>
      <TableRowColumn>{(this.web3.toDecimal(this.state.prices[index])) }</TableRowColumn>
      <TableRowColumn>{this.state.owners[index]}</TableRowColumn>
      <TableRowColumn>
        <RaisedButton label='Buy' onClick={() => this.state.productContract.buyProduct.sendTransaction(this.state.productids[index], { from: this.web3.eth.accounts[1], value:this.state.prices[index], gas:2000000 })} primary />
      </TableRowColumn>
    </TableRow>
});