如何在父锚点链接具有一个按钮作为其子元素时防止点击传播。

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

How to prevent click propagation when we have a parent anchor limk which has a button as one of children

问题

"When I click on the Link parent it fires the click on the button as well, I want both events to be separated."

"当我点击链接父元素时,它也触发了按钮的点击事件,我希望这两个事件分开。"

英文:

When I click on the Link parent it fires the click on the button as well, I want both events to be separated.

<Link className="product-item__link" to={`/products/${product.category}/${product.id}`} >
    <div className='product-item'>
        {/*I have here other elements*/}
        <button className="product-item__btn" onClick={() => addToCart(product)}>Add to cart</button>
     </div>
</Link>

答案1

得分: 1

Sure, here are the translated parts:

在按钮点击的函数调用中添加停止传播

更改函数定义

英文:

Add stop propagation in the function call of button click

<Link className="product-item__link" to={`/products/${product.category}/${product.id}`} >
    <div className='product-item'>
        {/*I have here other elements*/}
        <button className="product-item__btn" onClick={(e) => addToCart(e, product)}>Add to cart</button>
     </div>
</Link>

change function definition

const addToCart = (e, product) => {
      e.stopPropagation();
      e.preventDefault();
      //rest of the code...
}

huangapple
  • 本文由 发表于 2023年6月12日 20:32:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76456707.html
匿名

发表评论

匿名网友

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

确定