Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

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

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 Component {
  doSomething = () => {
    console.log('Hi');
  }
  render() {
    return (
      <Container>
        <Button onClick={this.doSomething} title="Test" /> 
        <Button onClick={() => this.doSomething()} title="Test" />
      </Container>
    );
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you don't need to pass the parameter, you can just use

{this.doSomething}

But if you need to pass the parameter to the function, then this will cause your method to execute immediately:

{this.doSomething(param)}

Thus, not to execute the function immediately, we need to use arrow method like you used:

{() => this.doSomething(param)}

Thus, in your case both are same. Because they are only executed when onClick is called ie. you click on the element.


Bonus:

You can still use the first way even you want to pass the parameter:

{this.doSomething(param)}

But for this, you need to define your method like this:

doSomething = (param) => () => {
  console.log('Hi');
}

Furthermore, if you wish to use event object, then you may use like below:

doSomething = (param) => (event) => {
  console.log('Hi');
}

Or, with the second approach ie. with arrow function:

{(event)=>this.doSomething(event,param)}

And obviously, if you are worried about performance, I would suggest not to use inline arrow function. The preferred way to use:

doSomething = (param1, param2,) => (event) => {

Misunderstanding:

Some people might find the method that pass the parameter without using inline arrow function will also work. But this is incorrect. Let me clarify on this.

When you use {this.doSomething(param)}, this function seems to work fine with its parameter. But if you change the state inside the handler, then you'll know the big difference. You'll get error maximum update depth exceeded react.

But with the same, you can avoid that error and also avoid the performance issue, you'll need to define the method like I stated before with arrow function:

doSomething = (param) => () => {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...