简体   繁体   中英

How to Stop Click Event Bubbling With e.stopPropagation() in React

I have a div which is wrapped in a Link tag in NextJS. Within the div I have a row of components which are buttons. When I click one of these buttons, they do what they should do, but the Link tag also gets fired from the parent div and we navigate to another page. I have added e.stopPropagation() to the event handlers of the buttons, but it's not making any difference. Can anyone see what I'm doing wrong, please?

The parent component:

<Link href={{
    pathname: `/...`,
    query: { 
        var:var 
    },
}}>
    <div>
    ...
        <div className="flex flex-row">
            <Button1/>
            <Button2/>
        </div>
    </div>    
</Link>

A child button component:

async function handleClick(e) {
    e.stopPropagation()
    ...
}

<button onClick={handleClick}>
...
</button>

I have also tried adding adding the stopPropagation to the onClick as such:

<button onClick={(e) => e.stopPropagation(), handleClick}>
...
</button>

Why is the click still bubbling up to the parent Link, please?

here is the culprit:

<button onClick={(e) => e.stopPropagation(), handleClick}>

try:

<button onClick={(e) => { e.stopPropagation(); handleClick(); }

live demo on these two different versions: https://codepen.io/remyho427/pen/NWamxvG

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM