简体   繁体   中英

Why methods as arrow functions work in react classes but not in normal classes?

We can declare methods of component class as arrow functions, like so:

class SomeComponent extends React.Component {
  someMethod = () => { // <<----- This does not throw error
    // some code
  }
}

..that won't throw any error, but below does:

class SomeNormalClass {
  someMethod = () => { // <<----- This throws error
    // some code
  }
}

It says unexpected = after someMethod . It works fine if I change my someMethod back to normal function instead of declaring it as an arrow function as shown below. Why?

class SomeNormalClass {
  function someMethod() { // <<----- This works fine
    // some code
  }
}

Your someMethod in first example is a property of the class, not a method. BabelJS support properties in classes, but native js not. You can see difference here . You should add some properties in constructor for Vanilla JS.

someMethod = () => {...} is class field. Class fields are stage 3 proposal which isn't natively supported and needs to be transformed by transpiler (Babel); someMethod class field is syntactic sugar for constructor code:

constructor() {
  this.someMethod = () => {
    // some code
  }
}

Both SomeComponent and SomeNormalClass are expected to work when used in same conditions. Neither of them will work natively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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