使用useEffect來保持背景顏色狀態的技巧
<p>我正在嘗試保存願望單切換按鈕的背景顏色,以便當用戶跨頁面時,按鈕的顏色保持為“黑色”,以向用戶顯示他們已經將該物品保存到願望單中。 </p>
<pre class="brush:php;toolbar:false;">const Item = (props) => {
const dispatch = useDispatch();
const [background, setBackground] = useState(false);
function addToCartHandler(product) {
dispatch(addToCart(product));
}
function toggleWishlistHandler(product) {
dispatch(toggleItem(product));
setBackground((current) => !current);
}
return (
<div>
<li className={classes.item}>
<img src={props.img} alt="Item" className={classes.image} />
<div className={classes.description}>
<p className={classes.title}>{props.title}</p>
<p className={classes.price}>£{props.price}.00</p>
</div>
<div className={classes.actions}>
<div
className={`${classes.addWishlist} ${classes.icon}`}
onClick={() => toggleWishlistHandler(props.product)}
style={{
backgroundColor: background ? "black" : "orange",
}}
>
<i className="fa-solid fa-heart"></i>
</div>
<div
className={`${classes.addCart} ${classes.icon}`}
onClick={() => addToCartHandler(props.product)}
>
<i className="fa-solid fa-bag-shopping"></i>
</div>
</div>
</li>
</div>
);
};
export default Item;</pre>