我可以在反应组件的构造函数中使用箭头函数吗?

编程入门 行业动态 更新时间:2024-10-10 13:21:29
本文介绍了我可以在反应组件的构造函数中使用箭头函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此问题类似于使用React时最好在构造函数中使用胖箭头函数或绑定函数,但有点不同。您可以在构造函数中将函数绑定到此,或者在构造函数中应用箭头函数。请注意,我只能在我的项目中使用ES6语法。

This question is similar to When using React Is it preferable to use fat arrow functions or bind functions in constructor? but a little bit different. You can bind a function to this in the constructor, or just apply arrow function in constructor. Note that I can only use ES6 syntax in my project.

1。

class Test extends React.Component{ constructor(props) { super(props); this.doSomeThing = this.doSomeThing.bind(this); } doSomething() {} }

2。

class Test extends React.Component{ constructor(props) { super(props); this.doSomeThing = () => {}; } }

这两种方式的优缺点是什么?谢谢。

What's the pros and cons of these two ways? Thanks.

推荐答案

选项1通常因某些原因更为可取。

Option 1 is generally more preferable for certain reasons.

class Test extends React.Component{ constructor(props) { super(props); this.doSomeThing = this.doSomeThing.bind(this); } doSomething() {} }

<原型方法比较简单。子类可以用

Prototype method is cleaner to extend. Child class can override or extend doSomething with

doSomething() { super.doSomething(); ... }

当实例属性

this.doSomeThing = () => {};

或ES.next类字段

or ES.next class field

doSomeThing = () => {}

代替,调用 super.doSomething()是不可能的,因为原型上没有定义方法。覆盖它将导致在父和子构造函数中分配 this.doSomeThing 属性两次。

are used instead, calling super.doSomething() is not possible, because the method wasn't defined on the prototype. Overriding it will result in assigning this.doSomeThing property twice, in parent and child constructors.

原型方法也是可达到mixin技术:

Prototype methods are also reachable for mixin techniques:

class Foo extends Bar {...} Foo.prototype.doSomething = Test.prototype.doSomething;

原型方法更可测。他们可以在课程实例化之前被窥视,扼杀或嘲笑:

Prototype methods are more testable. They can be spied, stubbed or mocked prior to class instantiation:

spyOn(Foo.prototype, 'doSomething').and.callThrough();

这允许在某些情况下避免竞争条件。

This allows to avoid race conditions in some cases.

更多推荐

我可以在反应组件的构造函数中使用箭头函数吗?

本文发布于:2023-10-26 17:55:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530908.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   箭头   组件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!