React onClick and preventDefault() link refresh/redirect?

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

I\'m rendering a link with react:

render: ->
  `upvote`

Then, above I hav

13条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 06:45

    I've had some troubles with anchor tags and preventDefault in the past and I always forget what I'm doing wrong, so here's what I figured out.

    The problem I often have is that I try to access the component's attributes by destructuring them directly as with other React components. This will not work, the page will reload, even with e.preventDefault():

    function (e, { href }) {
      e.preventDefault();
      // Do something with href
    }
    ...
    Go to Foobar
    

    It seems the destructuring causes an error (Cannot read property 'href' of undefined) that is not displayed to the console, probably due to the page complete reload. Since the function is in error, the preventDefault doesn't get called. If the href is #, the error is displayed properly since there's no actual reload.

    I understand now that I can only access attributes as a second handler argument on custom React components, not on native HTML tags. So of course, to access an HTML tag attribute in an event, this would be the way:

    function (e) {
      e.preventDefault();
      const { href } = e.target;
      // Do something with href
    }
    ...
    Go to Foobar
    

    I hope this helps other people like me puzzled by not shown errors!

提交回复
热议问题