Embedded button in link, how to stop the chain effect of onClick link
P粉553428780
P粉553428780 2023-08-17 21:31:04
0
1
453
<p>I have code similar to the example below. I'm trying to create a clickable grid cell that sends the user to a URL, but when the embedded image button is clicked I only want the onClick event to fire and no other events, is it possible to do this? I tried adding a call to stopPropagation, but after the first onClick is handled, it still links to the underlying link. </p> <pre class="brush:php;toolbar:false;">const handleSaveClick = async (e, activity, index) => { e.stopPropagation(); ... } <Grid item> <a className={clsx(classes.link)} href={payload.shareableUrl} onClick={() => handleLinkClick(payload.url, index)} > <Tooltip title={payload.title}> <Typography className={clsx(classes.copy)}> {payload.title} </Typography> </Tooltip> <Button className={clsx(classes.savedButton)} onClick={(e) => handleSaveClick(e, payload, index)} > <img className={clsx(classes.savedIcon)} src={payload.isSaved ? saved : notSaved} /> </Button> </a> </Grid></pre>
P粉553428780
P粉553428780

reply all(1)
P粉863295057

In the handleSaveClick function, you can use the e.preventDefault() function. When the embed image button is clicked, the handleSaveClick function will be executed, e.preventDefault() should prevent the default behavior of the link, ensuring that it does not navigate to the URL.

const handleSaveClick = async (e, activity, index) => {
  e.preventDefault(); // 阻止默认行为(跟随链接)
  e.stopPropagation(); // 阻止事件冒泡

  // 在这里添加你的按钮点击逻辑
  // ...
}

Additionally, you should consider replacing the anchor tag of a clickable area or button with another suitable element.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template