简体   繁体   中英

React button onClick property:

What is the difference between (1) and (2) in React ?

onClick={()=>handleDelete(id)} -------(1)

onClick={handleDelete(id)} ----------(2)

why does (2) cause infinite loops whereas (1) works just fine?

I couldn't find any documentation on onClick in react being only able to take in functions. I'm also a bit confused as to how the Html and JS onClick property is different from react So any documentation links will also be highly appreciated.

The code snippet in question:

<button
    className="btn btn--danger"
    onClick={()=>handleDelete(id)}
>
    Delete
</button>

Thanks in advance!

Whatever is in the curly braces is what is returned to the listener. The listener is expecting a function that will be called when the event is fired.

  1. onClick={handleDelete(id)}

This won't work because you're calling handleDelete immediately and assigning the result of calling that function to the listener. That function may return an explicit value or undefined (note: that explicit value may be aa new function (closure) which can be assigned to the listener - but in this case I doubt this is happening).

  1. onClick={() => handleDelete(id)}

This will work because you're assigning a function to the listener, and when the event is fired it will call that function which, in turn, will call handleDelete(id) .

  1. onClick={handleDelete}

This will also work because you're passing a reference to the handleDelete function to the listener, and that function will get called when the event is fired.

(Note: doing it this way would mean that the component would need to be rewritten to have a data-id attribute that the function can pick up because you're no longer sending an explicit id argument to handleDelete when you call it.)

before explaining the differences you have a mismatching braces in the second one

The second one is Called invoked function that means when the component mounts the function runs without clicking the button, it will invoke and runs it, and does not wait and will run immediately,and for the other one is callback function it will run when the user click the 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