autobind-decorator - 2018-05-28

  • 2018-05-28 創(chuàng)建

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

之前通常這樣實(shí)現(xiàn):

<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里手動(dòng)去綁定它。

@autobind

可通過(guò)@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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容