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

时间:2018-03-14 17:55:55

标签: reactjs lodash web3js

我尝试渲染一个表格,该表格会显示产品详细信息,并且每个行的最后一列都有一个购买按钮。问题是当我点击购买按钮时,表中的每个产品都被购买了。有什么想法吗?

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 个答案:

答案 0 :(得分:0)

我做了两件事:

  1. 我使用了_.map()函数而不是_.each()函数,因为它更快并且遵循React模式的不变性。
  2. 您错过了<TableRowColumn>元素周围的<RaisedButton>元素,这就是按钮将(click)应用于整个行而不仅仅是<RaisedButton>元素的原因
  3. // 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>
    });