What is the difference between both button click in the given React Component?

后端 未结 3 1086
情书的邮戳
情书的邮戳 2020-11-30 14:50

Is there any difference between both the button click event in the given component? Which is the preferred way to write?

export default class App extends Com         


        
3条回答
  •  青春惊慌失措
    2020-11-30 15:23

    First we will look when to use both:

    1. onClick={this.doSomething} : This is using class variable directly, but it cannot be used when we are required to pass parameters to the function. For that, the second way comes to rescue. A way to pass parameters to this is :

      onClick={this.doSomething.bind(params, this)}

    2. onClick={() => this.doSomething()}: you can pass parameters to the function as

      onClick={() => this.doSomething(param1, param2)}.

    Also, an important point to note, when the component re-renders, memory is allocated for the second one every time, while the first one just uses memory reference. So, first one is better if you don't have to pass parameters in the function.

提交回复
热议问题