最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is using "onClick={}" considered a bad practise? - Stack Overflow

programmeradmin0浏览0评论

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?

Share Improve this question asked Jul 26, 2019 at 13:37 glenn zegersglenn zegers 411 silver badge5 bronze badges 9
  • 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
 |  Show 4 more ments

3 Answers 3

Reset to default 9

The 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 mean onClick?

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.

发布评论

评论列表(0)

  1. 暂无评论