React实现:默认首个div添加active类,hover切换active类
实现map渲染元素的hover激活+默认首个元素激活
需求
通过map渲染的元素,hover时添加active类(当前功能正常),需要补充:未hover任何元素时,首个div自动添加active类。
现有代码
JSX部分
{WhatWeOfferData.map(({ img, title, para}, index) => { return ( <div className={`${style.card} ${addActive.index === index && addActive.show ? `${style.active}` : ""}`} onMouseEnter={hoverOn} onMouseLeave={hoverOff} key={index} data-id={index} > <Image src={img} alt="offer_images" width={37} height={41} /> <h2>{title}</h2> <p>{para}</p> </div> ); })}
状态与事件逻辑
let [addActive, setAddActive] = useState(false); const hoverOn = (e) => { setAddActive({ index: parseInt(e.currentTarget.dataset.id), show: true }); }; const hoverOff = (e) => { setAddActive({ index: parseInt(e.currentTarget.dataset.id), show: false }); };
解决方案
步骤1:简化状态管理
将原有的复合状态改为直接跟踪当前激活的索引,初始值设为0(首个元素的索引):
const [activeIndex, setActiveIndex] = useState(0);
步骤2:调整hover事件逻辑
- 移除单个元素的
onMouseLeave事件,改为给包裹所有map元素的容器添加onMouseLeave事件,当鼠标完全离开容器时,恢复首个元素的激活状态 - 修改
hoverOn事件,直接设置当前元素的索引为激活索引
// 包裹map元素的容器示例 <div className={style.cardContainer} onMouseLeave={() => setActiveIndex(0)}> {WhatWeOfferData.map(({ img, title, para}, index) => { return ( <div className={`${style.card} ${activeIndex === index ? style.active : ""}`} onMouseEnter={(e) => setActiveIndex(parseInt(e.currentTarget.dataset.id))} key={index} data-id={index} > <Image src={img} alt="offer_images" width={37} height={41} /> <h2>{title}</h2> <p>{para}</p> </div> ); })} </div>
步骤3:移除冗余的hoverOff函数
现在不需要单独的hoverOff函数,所有状态切换由hoverOn和容器的onMouseLeave处理。
逻辑说明
- 初始状态:
activeIndex为0,首个元素自动添加active类 - 鼠标hover任意元素:触发该元素的
onMouseEnter,将activeIndex设为当前元素索引,对应元素激活 - 鼠标在容器内的元素间切换:自动切换激活状态,无闪烁
- 鼠标移出整个容器:触发容器的
onMouseLeave,activeIndex重置为0,回到首个元素激活状态
内容的提问来源于stack exchange,提问作者Aslan
相关产品推荐
相关产品推荐

