Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

reactjs - React onClick and preventDefault() link refresh/redirect?

I'm rendering a link with react:

render: ->
  `<a className="upvotes" onClick={this.upvote}>upvote</a>`

Then, above I have the upvote function:

upvote: ->
  // do stuff (ajax)

Before link I had span in that place but I need to switch to link and here's the trouble - every time I click on .upvotes the page gets refreshed, what I've tried so far:

event.preventDefault() - not working.

upvote: (e) ->
  e.preventDefault()
  // do stuff (ajax)

event.stopPropagation() - not working.

upvote: (e) ->
  e.stopPropagation()
  // do stuff (ajax)

return false - not working.

upvote: (e) ->
  // do stuff (ajax)
  return false

I've also tried all of the above using jQuery in my index.html, but nothing seems to work. What should I do here and what I'm doing wrong? I've checked event.type and it's click so I guess I should be able to avoid redirect somehow?

Excuse me, I'm a rookie when it comes to React.

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A full version of the solution will be wrapping the method upvotes inside onClick, passing e and use native e.preventDefault();

upvotes = (e, arg1, arg2, arg3 ) => {
    e.preventDefault();
    //do something...
}

render(){
    return (<a type="simpleQuery" onClick={ e => this.upvotes(e, arg1, arg2, arg3) }>
      upvote
    </a>);
{

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...