简体   繁体   中英

Button within react-router Link?

Say I have an element with the following structure:

<Link to={`/games/${game.id}`}>
  <GameInfo/>
  <CustomButton/>
</Link>

在此处输入图像描述

Is it possible for the button inside the link to behave independently from the link beneath without using the z-index css property ? I'd like to do this while keeping the current behaviour in which hovering the button triggers both the hover effect for the button and for the link below.

Right now, if I click on the Add to Library button, the game gets added to the library but the Link below also gets triggered and the game profile page is open, which is not intended.

The only solution I can think of so far is something like this:

  <div> // <= move link hover effects here
    <Link to={`/games/${game.id}`}>
      <GameInfo/>
    </Link>

    <CustomButton/>
  </div>

But it's not ideal, because I would still like the area around the button to be part of the Link (so hover and the link itself work in the areas shown below).

在此处输入图像描述

Is z-index the only solution?

You can make use of preventDefault and stopPropagation to achieve this inside button click use like this below

<Link to="/game">
      <div>
      
        <button
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
           //function to do your stuff
          }}
        >
         Click Me
        </button>
      </div>
    </Link>

You can check the demo here

https://codesandbox.io/s/adoring-sun-dwnde?fontsize=14&hidenavigation=1&theme=dark

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