给定的React Component中的两个按钮单击之间有什么区别? [英] What is the difference between both button click in the given React Component?

查看:47
本文介绍了给定的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>
    );
  }
}

推荐答案

不需要传递参数时,只需使用

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)}


因此,在您的情况下,两者是相同的.因为它们仅在调用onClick时执行.您单击该元素.


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

奖金:

即使您要传递参数,您仍然可以使用第一种方法:

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) => {


误解:

某些人可能会发现不使用内联箭头功能而传递参数的方法也可以使用.但这是不正确的.让我澄清一下.

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.

使用{this.doSomething(param)}时,此函数似乎可以很好地使用其参数.但是,如果您更改处理程序内部的状态,那么您将知道最大的不同.您会收到错误消息,表示超过最大更新深度会做出反应.

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) => () => {

这篇关于给定的React Component中的两个按钮单击之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆