React中点击设为激活的元素,如何通过再次点击取消选中?
修改方案
你只需要调整点击判断逻辑、优化状态即可实现需求,具体修改如下:
- 移除冗余的
active2状态,直接通过active的值判断选中状态:active = -1对应无选中的默认状态,active = 索引值对应对应索引的图片被选中 - 点击事件中增加判断:如果当前点击的项已经是选中状态,就将
active重置为-1实现取消选中,否则更新为当前点击的索引 - 同步调整类名拼接逻辑,去掉对
active2的依赖
修改后的完整代码
import { useState, useRef, useEffect } from "react"; import "./App.css"; import { Data } from "./Data.js"; function App() { const scrollRef = useRef(); useEffect(() => { const el = scrollRef.current; if (el) { const wheelListener = (e) => { e.preventDefault(); el.scrollTo({ left: el.scrollLeft + e.deltaY * 5, behavior: "smooth" }); }; el.addEventListener("wheel", wheelListener); return () => el.removeEventListener("wheel", wheelListener); } }, []); const [active, setActive] = useState(-1); return ( <div ref={scrollRef} className="grid_container"> {Data.map((prev, i) => { return ( <div onClick={() => { // 新增判断:已选中则取消,否则切换选中 setActive(prevActive => prevActive === i ? -1 : i); console.log(prev.Team); }} className={`card ${active === i ? 'scale' : active !== -1 ? 'notScale' : ''}`} key={i} > <img src={prev.TeamBadge} alt="" /> </div> ); })} </div> ); } export default App;
内容的提问来源于stack exchange,提问作者Gangrel
相关产品推荐
相关产品推荐

