You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中点击设为激活的元素,如何通过再次点击取消选中?

修改方案

你只需要调整点击判断逻辑、优化状态即可实现需求,具体修改如下:

  1. 移除冗余的active2状态,直接通过active的值判断选中状态:active = -1对应无选中的默认状态,active = 索引值对应对应索引的图片被选中
  2. 点击事件中增加判断:如果当前点击的项已经是选中状态,就将active重置为-1实现取消选中,否则更新为当前点击的索引
  3. 同步调整类名拼接逻辑,去掉对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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:36:05