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

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

这个问题类似于当使用 React 时,最好在构造函数中使用粗箭头函数还是绑定函数? 但有点不同.您可以在构造函数中将函数绑定到 this ,或者在构造函数中仅应用箭头函数.请注意,我只能在我的项目中使用 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.

混合技术也可以使用原型方法:

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.

更多推荐

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

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

发布评论

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

>www.elefans.com

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