如何仅向父元素添加事件监听器

huangapple go评论79阅读模式
英文:

How to add an event listener only to a parent element

问题

我正在使用React开发一个电子商店卡片。我在父div上添加了onMouseOver和onMouseOut事件监听器。React会将这些事件监听器传播给所有子元素,因此每次光标进入或离开子元素时都会触发事件。我想要不同的行为 - 事件应该只在光标进入或离开父组件时触发,而不是其子元素。

我尝试在互联网上寻找解决方案,但令人惊讶的是,只有stopPropagation方法被提到。

React专家,请建议解决方案。

这是我的组件:

function GoodCardMod(props) {

    ...

    const handleMouseOverGoodCard = (event) => {
        console.log('Over');
    };
    const handleMouseOutGoodCard = (event) => {
        console.log('Out');
    };


    return (
        <div 
            className='good-card-container component-container'
            onMouseOver={handleMouseOverGoodCard}
            onMouseOut={handleMouseOutGoodCard}
        >
            <img 
                src={good.good_image} 
                alt={good.name} 
                className='good-card-image'>
            </img>
            <span className='good-card-title'>
                {good.name}
            </span>
            <span className='good-card-price'>
                {good.current_price} грн
            </span>
            <Button 
                size='small' 
                onClick={isInCart[0] ? () => {} : () => cartDispatcher(addToCartAction(cartGood))}
                variant="contained"
                className='good-card-button'
                color={isInCart[0] ? 'success' : 'primary'}
            >
                {isInCart[0] ? 'Вже у кошику' : 'У кошик'}
            </Button>
            <CharachteristicsList characteristics={good.good_characteristics} />
        </div>
    );
};

注意:在代码中,我将">"和"<"转换为实际的HTML标签符号,以便更清晰地显示代码。

英文:

I am developing an e-shop card with React. I added onMouseOver and onMouseOut event listeners to the parent div. React propagates these event listeners to all its children, so an event is triggered every time the cursor enters or leaves a child element. I want a different behaviour - the event should only be triggered when the cursor enters or leaves the parent component, not its children.

I tried to find the solution on the internet, but suprisingly only stopPropagation method was supposed.

React gurus, please advise the solution.

This is my component:

function GoodCardMod(props) {

    ...

    const handleMouseOverGoodCard = (event) =&gt; {
        console.log(&#39;Over&#39;);
    };
    const handleMouseOutGoodCard = (event) =&gt; {
        console.log(&#39;Out&#39;);
    };


    return (
        &lt;div 
            className=&#39;good-card-container component-container&#39;
            onMouseOver={handleMouseOverGoodCard}
            onMouseOut={handleMouseOutGoodCard}
        &gt;
            &lt;img 
                src={good.good_image} 
                alt={good.name} 
                className=&#39;good-card-image&#39;&gt;
            &lt;/img&gt;
            &lt;span className=&#39;good-card-title&#39;&gt;
                {good.name}
            &lt;/span&gt;
            &lt;span className=&#39;good-card-price&#39;&gt;
                {good.current_price} грн
            &lt;/span&gt;
            &lt;Button 
                size=&#39;small&#39; 
                onClick={isInCart[0] ? ()=&gt; {} : () =&gt; cartDispatcher(addToCartAction(cartGood))}
                variant=&quot;contained&quot;
                className=&#39;good-card-button&#39;
                color={isInCart[0] ? &#39;success&#39; : &#39;primary&#39;}
            &gt;
                {isInCart[0] ? &#39;Вже у кошику&#39; : &#39;У кошик&#39;}
            &lt;/Button&gt;
            &lt;CharachteristicsList characteristics={good.good_characteristics} /&gt;
        &lt;/div&gt;
    );
};

答案1

得分: 1

尝试在父组件的onMouseEnter中检查event.currentTarget === event.target。这将替代您当前代码中的onMouseOver

const mouseIn = (event) => {
    if (event.currentTarget === event.target) {
      console.log('进入');
   }
};
const mouseOut = (event) => {
    if (event.currentTarget === event.target) {
      console.log('离开');
   }
};
英文:

Try checking event.currentTarget === event.target in the onMouseEnter of your parent component. This would replace onMouseOver in your current code.

    const mouseIn = (event) =&gt; {
        if (event.currentTarget === event.target) {
          console.log(&#39;In&#39;);
       }
    };
    const mouseOut = (event) =&gt; {
        if (event.currentTarget === event.target) {
          console.log(&#39;Out&#39;);
       }
    };

huangapple
  • 本文由 发表于 2023年7月14日 00:15:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681462.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定