Skip to content Skip to sidebar Skip to footer

Es6 React: Will Es.next's @autobind Bind Methods Only Once For Each Instance?

There are a lot of questions/articles written on the numerous ways to handle binding in ES6 React, but most don't seem to address a problem outlined in the React docs (emphasis min

Solution 1:

Class instance fields and their associated initializers solve the issue of having to assign properties with the same name as methods inside the constructor but with a more succinct syntax. The following example is possible with Babel's class properties transform:

classCounterextendsReact.Component{
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
  }
  tick = () => {
    this.setState({count: this.state.count + 1});
  };
  ...
 }

This creates a new, bound tick property for each Counter instance. This creates the same number of bound functions as React.createClass did.

Without the instance field and initializer, the effect is the same (a bound tick property is created for each Counter instance) but with more verbose syntax:

constructor(props) {
  super(props);
  this.state = {count: props.initialCount};
  this.tick = this.tick.bind(this);
}
tick() {
  this.setState({count: this.state.count + 1});
}

Solution 2:

I wrote a small component that does binding all methods of other components. you can try it if you want: http://www.marouen-mhiri.com/react/autobinding-es6-classes-in-react-another-approach/

Post a Comment for "Es6 React: Will Es.next's @autobind Bind Methods Only Once For Each Instance?"