簡體   English   中英

如何更新表格行?

[英]How to update table row?

我有一個表格,顯示用戶選擇的項目。 現在,當用戶添加項目時,該項目將添加為新行。 我嘗試更改它,以便不是創建一個新行,而是增加一個數量。 然而,這不起作用,因為我得到一個錯誤,說我需要一個其他的后:

<table>
  <thead>
    <tr>
      <th>Item</th>
      <th>Amount</th>
    </tr>
  </thead>
  <tbody>
    {this.state.basket.map(item => {
      return (
        {this.getAmount(item) === 0 ? (
          <tr>
            <td>{item}</td>
            <td>{this.getAmount(item)}</td>
          </tr>
        ) : (
          this.updateAmount(item);
        )
      )
    })}
  </tbody>
</table>

如何更改此項以在項目旁邊有一個amount

獲取金額方法:

getAmount = item => {
  var amount = 0;
  var basket = [...this.state.basket];
  basket.forEach(i => {
    if (i === item) {
      amount++;
    }
  });
  console.log(item + " : " + amount);
  return parseInt(amount);
};

更新金額方法:

updateAmount = item => {
  return this.getAmount(item);
};

我是React的新手,但看起來你在'else'中調用的方法只是返回一些值,而不是jsx。 您的“ if”結果返回jsx,但是您的else只是調用一個僅返回值的函數。

getAmount = item => {
  var amount = 0;
  var basket = [...this.state.basket];
  basket.forEach(i => {
    if (i === item) {
      amount++;
    }
  });
  console.log(item + " : " + amount);
  return (
    <React.Fragment>
      <span>{parseInt(amount)}</span>
    </React.Fragment>
  )
};

自從我剛開始學習React以來,我很有可能會離開,但我認為如果有幫助的話,值得一試。 或者,您可能可以直接在else中執行<React.Fragment>部分,並將函數放在<span>內,但不確定是否可行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM