- 2018-05-28 创建
A class or method decorator which binds methods to the instance so this is always correct, even when the method is detached.
before
之前通常这样实现:
<button onClick={ this.handleClick.bind(this) }></button>
或
class InputControlES6 extends React.Component { 
  constructor(props) {
    super(props); 
    // Set up initial state
    this.state = {
      text: props.initialValue || 'placeholder' 
    };
    // Functions must be bound manually with ES6 classes
    this.handleChange = this.handleChange.bind(this); 
  } 
  handleChange(event) {
    this.setState({ 
      text: event.target.value
    });
  } 
  render() {
    return (
      <div>
        Type something:
        <input onChange={this.handleChange}
          value={this.state.text} />
      </div>
    );
  }
}
在声明handleChange后,再在constructor里手动去绑定它。
@autobind
可通过@autobind 快速绑定我们 class 中 constructor 外的 methods,
npm install autobind-decorator
import autobind from 'autobind-decorator'
 
class Component {
  constructor(value) {
    this.value = value
  }
 
  @autobind
  method() {
    return this.value
  }
}
 
let component = new Component(42)
let method = component.method // .bind(component) isn't needed!
method() // returns 42
 
 
// Also usable on the class to bind all methods
@autobind
class Component { }