【发布时间】:2021-01-10 17:53:46
【问题描述】:
借助 .map 函数,我得到了一个在屏幕上显示的对象列表。 它看起来像这样:
组件 1:
let itemList = [
{
type: "White T-shirt",
id: 1,
cost: 300,
image: whiteTshirt
},
{
type: "Purple T-shirt",
id: 2,
cost: 350,
image: purpleTshirt
},
{
type: "Baseballcap",
id: 3,
cost: 150,
image: whiteCap
},
{
type: "Vice Golfball",
id: 4,
cost: 40,
image: golfball
},
{
type: "Mousepad",
id: 5,
cost: 200,
image: mousepad
}
];
let products = itemList.map(items => {
let item =
<div key={items.id}>
<h2>{items.type}</h2>
<img className="image" src={items.image}></img>
<p className="price">${items.cost}</p>
<button onClick={onBuy} className="buy-btn">Buy</button>
</div>
return item;
})
return(
{shoppingcart ? <Component2 /> : null}
<main> {products} </main>
)
组件 2:
const Comopnent2 = props => {
const [webshop, setWebshop] = useState(false);
return(
<div>
{webshop ? <Webshop /> : null }
<a href="/Webshop" onClick={e => { e.preventDefault(); setWebshop(true)}} >
<p className="to-shop"> Back to shop</p></a>
<h2 className="shopping-header">Your Shopping Cart</h2>
<div className="cart-container">
// Here i want to object that i clicked display
</div>
)
}
我想要的是将一个特定对象推送到我拥有的另一个组件中的另一个数组。当我单击调用 onBuy 函数的按钮时,我想这样做。我该如何管理?谢谢。
【问题讨论】:
-
我不清楚你到底想要什么?您可以使用 .filter 过滤列表,但我不确定这是您正在寻找的内容
-
@adirabargil 我现在更新了我的问题 :)
标签: javascript reactjs arraylist javascript-objects push