Tips to use useEffect to maintain background color state
P粉131455722
P粉131455722 2023-08-18 15:08:53
0
1
477
<p>I'm trying to save the background color of the wishlist toggle button so that when the user moves across pages, the color of the button remains "black" to show the user that they have saved the item to the wishlist. </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>
P粉131455722
P粉131455722

reply all(1)
P粉642919823

You can save colors in local storage.

// 检查是否设置为黑色
  const [background, setBackground] = useState(localStorage.getItem('wishlistBackground') === 'black');


// 每当背景颜色发生变化时,将其保存到本地存储中
  useEffect(() => {
    localStorage.setItem('wishlistBackground', background ? 'black' : 'orange');
  }, [background]);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!