【问题标题】:How can I get single item's id in Ant Design table column rendering如何在 Ant Design 表格列渲染中获取单个项目的 id
【发布时间】:2020-11-08 02:48:47
【问题描述】:

这里 cartItems 是我作为数据源传递的数组!

<Table
        style={{ marginTop: '2rem' }}
        columns={columns}
        dataSource={cartItems}
     />

如何在 render() 方法内的 cartItems 数组中获取单个项目? 我只想提取 id 并将其传递到 deleteFromCart(id) 中。

  const columns = [
{ title: 'Name', dataIndex: 'name', key: 'name' },
{ title: 'Quantity', dataIndex: 'quantity', key: 'quantity' },
{ title: '$ Unit Price', dataIndex: 'price', key: 'price' },
{ title: '$ Total Price', dataIndex: 'totalPrice', key: 'totalPrice' },
{
  title: 'cartItem',
  dataIndex: 'cartItem',
  key: 'cartItem',
  render: (cartItem) => (
    <a
      style={{ color: 'red' }}
      onClick={(cartItem) => {
        deleteFromCart(cartItem.id)
        console.log('delete')
      }}
    >
      Remove
    </a>
  ),
},

]

我无法提取 id..请帮忙!

【问题讨论】:

    标签: javascript arrays reactjs rendering ant-design-pro


    【解决方案1】:

    第二个参数(记录)是数组中的特定记录!

    render: (item,record) => (    //second argument is the item
            <a
              style={{ color: 'red' }}
              onClick={(e) => {
                deleteFromCart(record.id)
              }}
            >
              Remove
            </a>
          ),
        },
    

    【讨论】:

      【解决方案2】:

      onClick 事件为您提供event 对象,而不是表的record。在您的情况下,由于变量名称相同,来自rendercartItem 被来自onClick handler 函数的cartItem 遮蔽

      {
        title: 'cartItem',
        dataIndex: 'cartItem',
        key: 'cartItem',
        render: (cartItem) => (
          <a
            style={{ color: 'red' }}
            onClick={(e) => { // remove cartItem from here
              deleteFromCart(cartItem.id)
              console.log('delete')
            }}
          >
            Remove
          </a>
        ),
      }
      

      【讨论】:

        猜你喜欢
        • 2012-10-20
        • 2020-07-23
        • 1970-01-01
        • 2021-12-02
        • 2020-04-27
        • 2020-10-28
        • 1970-01-01
        • 2021-08-04
        • 1970-01-01
        相关资源
        最近更新 更多