I learned that using onclick
is considered a bad practise in HTML. Right now I'm going through a React tutorial. The tutorial uses <button onClick={shoot}>Take the Shot!</button>
. Is this also considered a bad practise in React? And if it is, what is the "right" way to do it?
I learned that using onclick
is considered a bad practise in HTML. Right now I'm going through a React tutorial. The tutorial uses <button onClick={shoot}>Take the Shot!</button>
. Is this also considered a bad practise in React? And if it is, what is the "right" way to do it?
- 1 Possible duplicate of onclick or onClick? – ravibagul91 Commented Jul 26, 2019 at 13:40
-
2
@ravibagul91 I don't think this is relevant to this question. This is asking if you should use
onClick
in React, not about the DOM API. – VLAZ Commented Jul 26, 2019 at 13:42 -
1
@VLAZ yes, check this sandbox, you will see that in react,
onclick
don't work. – Vencovsky Commented Jul 26, 2019 at 13:46 - 1 There's a whole Handling Events section in the react docs that would have answered this for you – charlietfl Commented Jul 26, 2019 at 13:47
-
1
@Vencovsky thanks, I not too proficient in React. My first thought was that it's the same as the
onClick
HTML attrivute (well, more React-ified) as in it's case-insensitive but it seems it's not. – VLAZ Commented Jul 26, 2019 at 13:48
3 Answers
Reset to default 9The onclick
attribute in HTML is considered a bad practice because it decouples the function from the place where it was called from (among other things). If you read through the related JS files, it is unclear where a certain function was called from, and therefore its purpose is unclear. If you use .addEventListener
from within JS, you keep the function and the purpose (the events that trigger it) together.
Reacts purpose is to keep the logic and the view together, so there is no decoupling possible at all. Therefore it is totally fine to use onClick
, and it's the only right way I can think of.
No, in React is the usual way to handle a click event. It is not a good practice to do something like <button onClick={() => some_code_here}>Foo Bar</button>
because, in this way, you declare a new function on every render.
Just adding more information about the differences of onclick
and onClick
.
In react, onclick
won't work and onClick
is handled by react as you can see in this sandbox.
When using onclick
it might also give you a warning
Warning: Invalid event handler property
onclick
. Did you meanonClick
?
There is some reasons why onclick
is a bad practice, but in react, the correct way of handling clicks is passing a function to onClick
prop.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742372715a4431576.html
评论列表(0条)