简体   繁体   中英

How can I get single item's id in Ant Design table column rendering

Here cartItems is the array I passed as a datasource!

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

How can I get single item in my cartItems array inside the render() method? I just want to extract the id & want to pass it inside 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>
  ),
},

]

Im unable to extract the id..Please help!

onClick event gives you event object and not the record of table. In your case, since the variable name is same, cartItem from render is being shadowed by cartItem from onClick handler function

{
  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>
  ),
}

The second argument (record) is the particular record inside the array!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM