gpt4 book ai didi

javascript - react : event handling in ES8

转载 作者:行者123 更新时间:2023-11-30 11:17:22 25 4
gpt4 key购买 nike

我正在尝试使用 ES8 标准中最接近的事件处理方式。在 React 中,有什么区别:

  handleButtonPressSearch(inputValue) {
this.setState({
showAll: true
});
}

对比

  handleButtonPressSearch = (inputValue) => {
this.setState({
showAll: true
});
}

哪个是首选方式?

最佳答案

what is the difference in

您的第一个示例是方法。调用方法时,this 取决于调用方法的方式(与使用 function 关键字的传统函数一样)。因此,如果您将该方法的引用作为回调传递给其他代码(例如,事件处理程序),您需要确保将 this 设置为您的组件实例,而不是其他内容。

通常当您使用方法时,在构造函数中将它们绑定(bind)到实例:

this.handleButtonPressSearch = this.handleButtonPressSearch.bind(this);

你的第二个例子是使用 class fields语法和箭头函数。箭头函数不关心你用什么this调用它们,它们会忽略它;相反,他们使用在创建它们的上下文中的 this。对于类字段,这就是实例。因此,您不需要 bind 调用;该函数中的 this 将始终引用您的组件实例。

请注意,类字段语法仍然不是标准的 JavaScript,the proposal不过,目前处于第 3 阶段,大多数 React 项目都设置为允许您通过转译使用类字段。

Which is the preferred way?

两者都不是首选,这是一个风格问题。两者都可以访问实例,并且都可以在必要时使用 super(尽管在 React 中,通常不鼓励继承)。

关于javascript - react : event handling in ES8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51058031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com