在React中处理映射数组上的鼠标悬停事件



我正在尝试将悬停事件添加到从React中的数组映射的一组元素中。悬停时,我希望显示或隐藏一个元素。该功能在基本级别上起作用,但它会影响列表中的每个元素。我如何才能让它只是悬停在上面的单个元素具有这种效果?

const [addToCart, setAddToCart] = useState(false);
const showCartHandler = ()=>{
setAddToCart(true);
}
const hideCartHandler=()=>{
setAddToCart(false)
}

{selectedProducts.map((selectedProduct)=>(
<Chakra.VStack align="start" justify="start">
<Chakra.Box position="relative" 
onMouseLeave={showCartHandler} onMouseEnter={hideCartHandler}>
<Chakra.Image className={Styles.productImage} width= '300px'height="400px" src= 
{selectedProduct.image.src} position="relative"/>
<Chakra.Button 
position="absolute" 
bottom="0" width="100%" 
left="0" 
cursor="pointer" 
textTransform="uppercase" 
color="white" 
background="black" 
fontSize="13px" 
border="none" 
padding="10px"
className={Styles.Cart}
display={addToCart?'none':'block'}/>
))}

因为这是一个列表,所以最好将其更改为索引活动/悬停状态,而不是布尔状态:

const [hoveredCart, setHoveredCart] = useState(-1);
const showCartHandler = (i)=>{
setHoveredCart(i);
}
const hideCartHandler=()=>{
setHoveredCart(-1)
}

{selectedProducts.map((selectedProduct,i)=>(
<Chakra.VStack align="start" justify="start">
<Chakra.Box position="relative" 
onMouseLeave={hideCartHandler}
onMouseEnter={()=>showCartHandler(i)}>
<Chakra.Image className={Styles.productImage} width= '300px'height="400px" src= 
{selectedProduct.image.src} position="relative"/>
<Chakra.Button 
position="absolute" 
bottom="0" width="100%" 
left="0" 
cursor="pointer" 
textTransform="uppercase" 
color="white" 
background="black" 
fontSize="13px" 
border="none" 
padding="10px"
className={Styles.Cart}
display={hoveredCart === i? 'block':'none'}/>
))}

您可以添加一个索引来标记有问题的行

const [addToCart, setAddToCart] = useState(false);
const [selectedItemIndex, setSelectedItemIndex] = useState(-1);
const showCartHandler = ()=>{
setAddToCart(true);
setSelectedItemIndex(-1);
}
const hideCartHandler=(index)=>()=>{
setAddToCart(false)
setSelectedItemIndex(index);
}
//and then modify the boolean expression
{selectedProducts.map((selectedProduct,index)=>(
<Chakra.VStack align="start" justify="start">
<Chakra.Box position="relative" 
onMouseLeave={showCartHandler} onMouseEnter={hideCartHandler(index)}>
<Chakra.Image className={Styles.productImage} width= '300px'height="400px" src= 
{selectedProduct.image.src} position="relative"/>
<Chakra.Button 
position="absolute" 
bottom="0" width="100%" 
left="0" 
cursor="pointer" 
textTransform="uppercase" 
color="white" 
background="black" 
fontSize="13px" 
border="none" 
padding="10px"
className={Styles.Cart}
display={addToCart && selectedItemIndex != index ?'none':'block'}/>
))}

最新更新