简体   繁体   中英

Why are there different syntax of methods inside extending React.Component?

I notice that inside class ExampleComponent extends React.Component {...} there are different ways of defining methods, with the former being a declaration for methods that is part of React and the latter being expressions for your own methods. Why is this? Why aren't they both in the same format?

  componentDidMount() {
    ...
  }

vs.

  myMethod = () => {
    ...
  }

This one goes to prototype

fnProto() {

}

This one is experimental and goes directly to instance having this always refering to the instance.

fnInstance = () => {}

Translating to ES5

class Cmp {
 fnProto() {
   console.log('goes to proto')
 }

  fnInstance = () => {
    console.log('goes to instance')
  }
}

Will be roughly equivalent to

function Cmp() {
   this.fnInstance = (function() {
      console.log('goes to instance')
   }).bind(this)
}

Cmp.prototype.fnProto = function() {
   console.log('goes to proto')
}

When you have

componentDidMount() {
    ...
  }

it is a lifecycle function and this inside it is automatically bound by default to the React Component context.

However when you define your own function, this inside it will refer to the content of the function itself. However if you define it using an arrow function like

myMethod = () => {
    ...
  }

this keyword inside it will refer to the parent context which in this case is the React Component context.

Check this article on Arrow function

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