当不同组件中某个元素的onClick事件发生时,如何更改组件中某一元素的样式



基本上,每当单击"产品"组件中的"添加到购物篮"按钮时,我都希望页眉组件中的购物袋闪烁或展开。

产品组成:

import "../styles/Product.css";
import React, { useState } from "react";
import { useStateValue } from "../StateProvider";
function Product({ id, title, image, price, rating }) {
const [{ basket }, dispatch] = useStateValue();
const addToBasket = () => {
dispatch({
type: "ADD_TO_BASKET",
item: {
id: id,
title: title,
image: image,
price: price,
rating: rating,
},
});
};
return (
<div className="product">
<div className="product_info">
<p>{title}</p>
<p className="product_price">
<small>$</small>
<strong>{price}</strong>
</p>
<div className="product_rating">
{Array(rating)
.fill()
.map((_, i) => (
<p>🌟</p>
))}
</div>
</div>
<img src={image} alt="" />
<button onClick={addToBasket}>Add to Basket</button>
</div>
);
}
export default Product;

标题组件:

import React from "react";
import "../styles/Header.css";
import SearchIcon from "@mui/icons-material/Search";
import ShoppingBasketIcon from "@mui/icons-material/ShoppingBasket";
import { Link } from "react-router-dom";
import { useStateValue } from "../StateProvider";
const Header = () => {
const [{ basket, user }, dispatch] = useStateValue();
return (
<div className="header">

<div className="header_nav">

<Link to="/checkout">
<div className="header_optionBasket">
<ShoppingBasketIcon />
<span className="header_optionLineTwo header_basketCount">
{basket?.length}
</span>
</div>
</Link>
</div>
</div>
);
};
export default Header;

单击"添加到购物篮"按钮后,我们将如何使标题组件中的购物袋闪烁或展开?

我们想使用状态挂钩吗?

您可以使用React的内置上下文或任何其他第三方状态管理库,如redux或zustand。否则,您可以简单地将状态从通用父组件传递到每个组件。

将useEffect添加到您的购物车组件以侦听将要更改的变量,例如购物篮

注意:这将在您的购物车组件中

// You can use gsap or any other css library here
const tl = gsap.timeline()
const basketDiv = useRef(null)
useEffect(()=>{
tl.from(basketDiv.current,{
1, duration:
scale: 0.7,
ease: Bounce.easeIn
})
},[basket])
// and whenever the value of basket changes it will run the animation

您可以查看如何将Gsap与ReactJs一起使用。

我希望这对有帮助

最新更新