简体   繁体   中英

How to execute onclick before navigating to a different page?

I am working in React and I have the following scenario.

  <a href={link} variant="primary" onClick={this.onClickDoSomething}>
                          here.
  </a>

Now, I want the onclick to execute before the link has been clicked. However I do not see it happening.

How to work around this issue ? Thanks.

Note the onclick() will fire before the page is redirected. It appears that you may want to handle your navigation within your onclick function as opposed to having an href attribute. By doing it this way you can conditionally redirect (if need be) and/or wait for some async code to complete.

 onClick = url => { alert('Do something'); window.location.href = url; } 
 <a href='#' onclick="onClick('https://stackoverflow.com')">here.</a> 

React snippet:

 class App extends React.Component { onClickDoSomething = link => ev => { alert(link); // Do any operations here window.location.href = link; } render() { const link = 'https://stackoverflow.com'; return <div> <a href='#' onClick={this.onClickDoSomething(link)}>here.</a> </div>; } } ReactDOM.render( <App/> , document.querySelector("#app")) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id='app'></div> 

your click handler should be like this

onClickDoSomething=(link)=>{
//do something,then redirect to given link
window.location.href=link

}

and you should render link as

<a  variant="primary" onClick={()=>{this.onClickDoSomething(link)}}>
                      here.
</a>

First will suggest use react router but if link is external then another way is keep href="#" and write onclickHandler function at the end onclickHandler just use window.location=[link]

you want to visit

Hope it helps

All the given answers (ie using # for the href then adding window.location to your click handler) should work perfectly.

However, in case you're looking for another solution, you can also try making the link a button instead of an anchor tag, and just styling it as a button. Below I've done so using Bootstrap, but you could do so with just plain CSS as well:

 handleClickExamQuestions = function(URL){ window.location=URL }
 <button class="btn btn-link" onClick = {()=>this.handleClick(URL)}>Click Me</button>

You can use the mouseenter event, which is triggered when you hover over the link. Which means, it would be triggered before click event

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