[英]I have a dynamic html template. Which forms when I click on a button. Now, the problem is When I click on one button all buttons are clicked
[英]I do not want all the "addToBasket" buttons to change when i click on a specefic "addToBasket" button. Only the clicked button should change
單擊“添加到購物籃”按鈕時,該特定按鈕應替換為-
和+
按鈕。 現在所有映射的按鈕都在同時更改。
如何僅對一個“添加到購物車”按鈕進行更改?
使用:React、Chakra UI 按鈕和.map
函數。
{products.map((item) => {
return (
<Box key={item.id} border="1px solid black" h="auto" >
<Link to={`/product/single-product/${item.id}`}>
<Box h="auto" border="1px solid black">
<Box><Image src={item.image} h="fit-content" /></Box>
<Text h="fit-content" >{item.name}</Text>
<Text h="fit-content" >Rs.{item.price}</Text>
</Box>
</Link>
<Box align="center" border="1px solid black" h="50px" >
{ addToBasket && <Button onClick={() => handleAddToBasket(item)} ml="5px" >ADD TO BASKET</Button> }
{ addBtn && <Button ml="5px" onClick={handleReduceItem} >-</Button> }
{ addBtn && <Button ml="5px" >+</Button> }
</Box>
</Box>
)})}
按鈕 onClick 函數在這里:
const [addToBasket, setAddToBasket] = useState(true);
const [addBtn,setAddBtn] = useState(false);
function handleAddToBasket(singleProduct){
if(addToBasket === true){
setAddToBasket(false)
setAddBtn(true);
}
dispatch(addToCart(singleProduct))
}
function handleReduceItem(){
if(addBtn === true){
setAddToBasket(true)
setAddBtn(false);
}
}
此解決方案僅適用於添加到購物籃按鈕。 注意:您可以使用您的 Redux 存儲狀態。 我只使用本地狀態。
首先,您正在為所有產品使用 addToBasket 狀態,它是布爾值。 因此,無論何時更改 addToBasket 的狀態,都會對所有產品產生影響。
將此布爾值更改為數組。
const [basket, setAddToBasket] = useState([]);
在 handleAddToBasket 中進行此更改。
const [basket, setAddToBasket] = useState([]);
const [addBtn,setAddBtn] = useState(false);
function handleAddToBasket(singleProduct){
if(!basket.includes(singleProduct.id)){
setAddToBasket((ids) => [...ids, singleProduct.id])
setAddBtn(true);
dispatch(addToCart(singleProduct))
} else {
const newBasket = basket.filter((id) => id !== singleProduct.id)
setAddToBasket(newBasket)
// call your remove from cart dispatch here or however you want to handle it
}
}
在 jsx 中
<Button onClick={() => handleAddToBasket(item)} ml="5px" >{basket.includes(item.id) ? 'ADDED' : 'ADD TO BASKET' }</Button>
我認為不只是隱藏按鈕,你應該顯示一個文本ADDED
for already 然后你可以切換你的購物車中的項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.