5

Is there a better way to link "that" in the React Component classes?

 3 years ago
source link: https://www.codesd.com/item/is-there-a-better-way-to-link-that-in-the-react-component-classes.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Is there a better way to link "that" in the React Component classes?

advertisements

I'm currently working on a react app, and I find having to bind this a bit cumbersome when a component class has many functions.

Example

class Foo extends Component {
  constructor(props){
    super(props);
    this.function1 = this.function1.bind(this);
    this.function2 = this.function2.bind(this);
    this.function3 = this.function3.bind(this);
  }
  function1() {
    ...
  }
  function2() {
    ...
  }
  function3() {
    ...
  }
}

Is there a more efficient way to do this?


You can avoid having to bind methods by using the transform-class-properties Babel plugin, which is an experimental ES7 feature. Make sure you enable stage-0 in order to use it.

This allows the use of arrow functions when defining your class methods, leveraging arrow functions' lexical binding so this refers to function's context (in this case the class), like so:

class Foo extends Component {
    boundFunction = () => { /* 'this' points to Foo */ }
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK