- 2018-05-28 創(chuàng)建
A class or method decorator which binds methods to the instance so this is always correct, even when the method is detached.
before
之前通常這樣實現(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里手動去綁定它。
@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 { }