简体   繁体   English

为什么箭头函数可以在ReactJS类上使用而不能在纯ES6类上使用?

[英]Why arrow functions can be used on ReactJS classes but not on a pure ES6 class?

I was wondering to know if I can write a pure ES6 class using arrow functions. 我想知道是否可以使用箭头函数编写纯ES6类。 Here is my class example: 这是我的课程示例:

class PhoneNumber {
    constructor(phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    testEmpty() {
        if (!this.phoneNumber) return true;
        return false;
    }
}

Doen't seem that I can write it as: 看来我不能这样写:

class PhoneNumber {
    constructor = phoneNumber => {
        this.phoneNumber = phoneNumber;
    }

    testEmpty = () => {
        if (!this.phoneNumber) return true;
        return false;
    }
}

Altough I can write something similar on React: 我可以在React上写一些类似的东西:

   class PhoneNumber extends React.Component {
         state = {
              phoneNumber: this.props.phoneNumber;
         }

         testEmpty = () {
             if (!this.state.phoneNumber) return true;
             return false;
         }
     }

Why React component, even being a class, accepts the ES6 arrow function and my pure class doesn't ? 为什么React组件,即使是一个类,也接受ES6箭头函数,而我的纯类却不接受?

Constructor cannot be an arrow function at all. 构造函数根本不能是箭头函数。 You can create arrow methods in react because react uses proposals for class fields under the hood. 您可以在react中创建箭头方法,因为react在幕后使用了针对类字段的建议。 You can add them to your project with babel proposal plugins. 您可以使用babel提案插件将它们添加到您的项目中。 The benefit of using arrow class methods is that value of this in such a method would refer to class itself inside a callback. 使用箭头类方法的好处是,在这种方法中, this的值将在回调内引用类本身。 So you can use arrow methods inside of an event listener without wrapper function or without bind(). 因此,您可以在没有包装函数或没有bind()的情况下在事件监听器中使用箭头方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM