React onClick and preventDefault() link refresh/redirect?

前端 未结 13 768
生来不讨喜
生来不讨喜 2020-11-30 06:04

I\'m rendering a link with react:

render: ->
  `upvote`

Then, above I hav

相关标签:
13条回答
  • 2020-11-30 06:49

    A nice and simple option that worked for me was:

    <a href="javascript: false" onClick={this.handlerName}>Click Me</a>
    
    0 讨论(0)
  • 2020-11-30 06:49

    This is because those handlers do not preserve scope. From react documentation: react documentation

    Check the "no autobinding" section. You should write the handler like: onClick = () => {}

    0 讨论(0)
  • 2020-11-30 06:49

    If you are using React Router, I'd suggest looking into the react-router-bootstrap library which has a handy component LinkContainer. This component prevents default page reload so you don't have to deal with the event.

    In your case it could look something like:

    import { LinkContainer } from 'react-router-bootstrap';
    
    <LinkContainer to={givePathHere}>
        <span className="upvotes" onClick={this.upvote}>upvote</span>
    </LinkContainer>
    
    0 讨论(0)
  • 2020-11-30 06:56

    I didn't find any of the mentioned options to be correct or work for me when I came to this page. They did give me ideas to test things out and I found that this worked for me.

    dontGoToLink(e) {
      e.preventDefault();
     }
    
    render() {
      return (<a href="test.com" onClick={this.dontGoToLink} />});
    }
    
    0 讨论(0)
  • 2020-11-30 06:59

    render: -> <a className="upvotes" onClick={(e) => {this.upvote(e); }}>upvote</a>

    0 讨论(0)
  • 2020-11-30 07:02

    In a context like this

    function ActionLink() {
      function handleClick(e) {
        e.preventDefault();
        console.log('The link was clicked.');
      }
    
      return (
        <a href="#" onClick={handleClick}>
          Click me
        </a>
      );
    }
    

    As you can see, you have to call preventDefault() explicitly. I think that this docs, could be helpful.

    0 讨论(0)
提交回复
热议问题