美文网首页
autobind-decorator - 2018-05-28

autobind-decorator - 2018-05-28

作者: 勇敢的小拽马 | 来源:发表于2018-05-28 19:01 被阅读0次
  • 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

相关文章

网友评论

      本文标题:autobind-decorator - 2018-05-28

      本文链接:https://www.haomeiwen.com/subject/uyygjftx.html