const Test = ({ inventory }) =>
<div className="row">
{inventory.map((item, i) =>
<div className="item" key={"item_" + i}>
<div className="card hoverable col s3">
<img onClick={buyItem(i)} src={item.img} alt="" />
<div className="container center-align">
<h4 className="">
{item.name}
</h4>
<p>
Price: {item.price}
</p>
<p>
Average price paid: {item.averageDisplay}
</p>
<p>
Amount owned: {item.owned}
</p>
<button
className="btn"
data={item.index}
onClick={sellItem(i)}
name="button"
>
Sell
</button>
</div>
</div>
</div>
)}
</div>;
ReactDOM.render(<Test inventory{inventory}/>,
document.getElementById("container")
);
inventory 是一个对象数组,我已经成功地能够在这个示例中循环,但由于某种原因,我无法弄清楚如何将 i 的值传递到函数中,尽管它已经被用来生成唯一的 key 。
最佳答案
您需要创建一个新函数
onClick={() => sellItem(i)}
关于javascript - 如何将数组的索引传递到reactJs onClick 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45418554/