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

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

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.

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

答案1

得分: 1

Sure, here are the translated parts:

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

更改函数定义

英文:

Add stop propagation in the function call of button click

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

change function definition

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

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:

确定