Reputation: 8152
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
}
}
Upvotes: 0
Views: 83
Reputation: 222369
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.
Upvotes: 0