使用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>