简体   繁体   中英

React, button with link and onClick

I have this component:

      <ButtonSendMoney
        handleSendMoney={handleSendMoney}
        link={link}
      />

This one renders this:

  <Link to={link}>
    <button
      onClick={handleSendMoney}
    >
     Go
    </button>
  </Link>

So, my problem is my handleSendMoney handler is setting the link , in other words:

When I click the button, some actions are triggered, that modifies the value of link but with that code, it will navigate to the link value before be modified. So how could I "await" and wait for the handler be finished and then pass the proper link props to the component?

Edit:

I could edit the component, remove that and just redirect inside the handler mentioned above, but how?

I dont think that render a button inside a Link is a good idea, since you are triggering two dependent events.

In case you are using react-router-dom, you should do some think like this in your handleSendMoney function:

import React from 'react';
import { useHistory } from 'react-router-dom';

export default Exemple(){

  const history = useHistory()
  handleSendMoney(){
      //modifies the value of link
      history.push(link)
  }

  return(
      <ButtonSendMoney
        handleSendMoney={handleSendMoney}
        link={link}
      />
  );

}

And your ButtonSendMoney should be like:

 <button onClick={handleSendMoney}>
   Go
 </button>

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