autobind-decorator - 2018-05-28

  • 2018-05-28 创建

autobind-decorator

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 { }

ES7

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容