【问题标题】:Need a active class on first div在第一个 div 上需要一个活动类
【发布时间】:2022-11-23 17:41:55
【问题描述】:

我正在尝试通过悬停在地图元素上添加一个活动类。一切都很完美,但是当我没有将鼠标悬停在任何 div 上时,我需要在第一个 div 上添加一个活动类。

这是我的代码...

{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
    });
  };

【问题讨论】:

    标签: javascript node.js reactjs


    【解决方案1】:

    如果索引为零且状态未显示任何内容,则返回活动类

    className={`${style.card} ${getClass(index)}`}
    
    
    const getClass = (index) => {
        if(addActive.index === index && addActive.show )
           return style.active
    
        if(index === 0){
           if(!addActive.show) return style.active
        }
    
        return ""
    }
    

    【讨论】:

      【解决方案2】:

      只需这样做:

      {
        WhatWeOfferData.map(({ img, title, para}, index) => {
          return (
            <div className={`${style.card} ${addActive.index === index && addActive.show ? `${style.active}` : index === 0 ? `${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>
          );
      })}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-21
        • 2020-11-11
        • 2011-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多