英文:
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...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论