我是React的新手。尝试制作一个购物车,其中有一组数据作为要出售的商品,这些商品正在循环显示并在DOM上显示为Cards。我想知道用户单击数组中的哪个项目,以便将其添加到购物车中。
这是我的代码。如果我不确定,请问任何问题
import React, { Component } from "react";
import "./css/Card.css";
import Data from "./DummyData";
class Card extends Component {
state = {
zoom: false,
NumberOfItemsInCart: 0,
itemsInCart : [] ,
selectedCard : ''
};
render() {
// Method Target the selected Card and Zoom it
const handleCheck = (e) => {
this.setState({
zoom : true,
selectedCard : ?????
})
};
const addItem = () => {
this.props.addItemToCart(this.state.NumberOfItemsInCart)
//////////// ADD THE NAME OF THE ITEM SELECTED in Cart Array /////////
}
const DeleteItem = () => {
this.props.DeleteItemFromCart(this.state.NumberOfItemsInCart)
//////////// DELETE THE NAME OF THE ITEM SELECTED From Aray /////////
}
return (
<div className="band">
{Data.map((item, index) => {
return (
<div key={item.id} className="items" onClick={handleCheck} index={this.state.index}>
<div className="thumb">{item.title} </div>
<img className="item-images" src={item.img} alt={item.title} />
<div className="item-footer"> Price ${item.price}/lb </div>
<button className="btn btn-details" > Details </button>
<button onClick={addItem} className="btn btn-danger"> + </button>
<button onClick={ DeleteItem} className="btn btn-danger"> - </button>
</div>
);
})}
</div>
);
}
}
export default Card;
最佳答案
您可以将id作为参数传递,更改
onClick={handleCheck}
至
onClick={() => handleCheck(item.id)}
和
handleCheck()
到const handleCheck = (id) => {
this.setState({
zoom : true,
selectedCard : id
})
};
关于javascript - 在 map 功能中定位点击的卡索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50830735/