What is the difference between the two ways to define a React class method in ES6

I see this very much in ES6 React code

class Foo extends React.Component {
  bar = () => {
    console.log("bar")
  }

  baz() {
    console.log("baz")
  }
}

It seems that both of them define the methods barand bazon Foo, but how they differ.

+4
source share
3 answers

Declarations differ in how functions are written and contextfrom this,

In the first syntax

bar = () => {
    console.log("bar")
  }

a function is written using Arrow functionsyntax.

The arrow function does not have its own this; The value thisused is the enclosed version context. Therefore, the keyword thisinside this function will refer to the contextReact class

However second announcement

baz() {
    console.log("baz") 
}

- , this keyword .

, / React, this.state this.setState, ( - ( )), , this , . , , this this.setState - .

React

+9

.

, , ...

, , , , .

React, , , , , , , super,

class Button extends React.PureComponent {

    // class method - overridable in subclass
    pressMethod: function(): void {
      console.log('beep')
    }

    // instance property functions - only overwriteable in subclass
    pressArrow = (): void => {
      console.log('boop')
    }

    pressArrowTwo = (): void => {
      console.log('blip')
    }

  }


  class BigRedButton extends Button {

    // class method - overides subclass one, 
    // can call superclass method via `super`
    pressMethod: function(): void {
      super.pressMethod() // prints 'beep' to console
      console.log('BOOOOOOOOM!!!')
    }

    // instance property function
    // cannot call superclass via `super` as lambda have no prototype
    pressArrow = (): void => {
      super.pressArrow() // TypeError - not a function
      console.log('BOOOOOOOOM!!!')
    }

    // completely overwrites instance property of same name in subclass
    // doesn't try to access prototype so won't error but is limited
    pressArrowTwo = (): void => {
      console.log('BOOOOOOOOM')
    }

  }
+1

For simplicity, both are equal:

  • bar = () => {...}
  • this.bar = this.bar.bind (this)
0
source

Source: https://habr.com/ru/post/1690111/


All Articles