Next.js结合GSAP实现标题悬停动态展示对应图片的问题排查
问题原因
你当前的实现中,gsap使用全局类名.imgHome匹配所有图片元素,触发悬停时会控制列表内所有同类名的图片显隐,所以会出现所有图片同时显示的问题。
修复方案
只需调整两个部分:
- 给悬停事件传入当前遍历项的唯一id,仅控制对应行内的图片
- 缩小gsap的选择范围,只选中当前悬停行内的图片元素
修改后的完整代码如下:
import React, { useRef } from "react"; import { Row, Col } from "react-bootstrap" import Link from "next/link"; import gsap from "gsap"; import { getStrapiMedia } from "../lib/media"; const Articles = ({ articles }) => { const itemsRef = useRef({}); const handleHover = (id) => { // 仅选中当前id对应行内的图片 const currentImg = itemsRef.current[id]?.querySelector('.imgHome') if (!currentImg) return gsap.to(currentImg, { display: "block" }) } const handleHoverExit = (id) => { const currentImg = itemsRef.current[id]?.querySelector('.imgHome') if (!currentImg) return gsap.to(currentImg, { display: "none" }) } return ( <div> <div className="tableau"> {articles.map((item) => ( <Row key={item.id} // 传入当前项的id onMouseEnter={() => handleHover(item.id)} onMouseOut={() => handleHoverExit(item.id)} ref={el => (itemsRef.current[item.id] = el)}> <Link href={`/article/${item.id}`}> <a className="titre">{item.title} </a> </Link> <img className="imgHome" src={getStrapiMedia(item.image.url)} width="800" style={{display: 'none'}} // 初始默认隐藏,也可以写在全局CSS里 /> </Row> ))} </div> </div> ) } export default Articles
你也可以选择在全局CSS中添加.imgHome { display: none; }实现初始隐藏,不需要写在行内样式中。
内容的提问来源于stack exchange,提问作者Rom-888
相关产品推荐
相关产品推荐

