2 回答
TA贡献1789条经验 获得超10个赞
您可以向下传递处理程序并让孩子将详细信息传递给它,如下所示:
items.map(item => <Item addToCart={addToCart} {...item} />)
const Item = ({ id, name, addToCart }) =>
<div>
{name}
<button onClick={() => addToCart(id)}>Add to Cart</button>
</div>
或者像这样传递一个包含值的回调:
items.map(item => <Item addToCart={() => handleAddToCart(item.id)} {...item} />)
const Item = ({ id, name, addToCart }) =>
<div>
{name}
<button onClick={addToCart}>Add to Cart</button>
</div>
TA贡献1828条经验 获得超13个赞
在<Home />组件中,首先您可以使用 as 引入一个新状态useState:
const [selectedItem, setSelectedItem] = useState(null)
然后向下传递道具,setSelectedItem以便能够在那里触发:
<Card key={d.id} title={d.title} price={d.price} handleAddToCart={handleAddToCart}
setSelectedItem={setSelectedItem} />
然后在<Card />组件中用作:
const Card = ({id, title, price, setSelectedItem}) => {
return (
<>
<div key={id}>
<p>{title}</>
<p>{price}</>
<button onClick={() => {
handleAddToCart();
setSelectedItem({ id, title, price});
}}>Add to cart</button>
</div>
</>
)
}
+1 建议:
<Card />我会将一个属性中的详细信息传递给组件,如下所示:
<Card key={d.id}
data={d}
handleAddToCart={handleAddToCart}
setSelectedItem={setSelectedItem} />
然后将内部解构为:
const Card = (props) => {
const { data, setSelectedItem, handleAddToCart } = props
const { id, title, price } = data
// more code
}
添加回答
举报