- 當使用es5時,是不需要用.bind()的。
當使用es5 時,React會自動幫助我們給每一個function綁定一個this,所以我們不再需要手動綁定。
例如:
var HelloWorld = React.createClass({
getInitialState() {
return { message: 'Hi' };
},
logMessage() {
// this magically works because React.createClass autobinds.
console.log(this.state.message);
},
render() {
return (
<input type="button" value="Log" onClick={this.logMessage} />
);
}
});
- 當使用es6時,es6不會再自動的幫助我們綁定函數,這時我們就需要使用.bind(this).
例如:
class HelloWorld extends React.Component {
constructor(props) {
super(props);
this.state = { message: 'Hi' };
}
logMessage() {
// This works because of the bind in render below.
console.log(this.state.message);
}
render() {
return (
<input type="button" value="Log" onClick={this.logMessage.bind(this)} />
);
}
}
- 在es6中,我們也可以使用箭頭函數來避免使用.bind(this)
例如:
class HelloWorld extends React.Component {
constructor(props) {
super(props);
this.state = { message: 'Hi' };
}
logMessage() {
// This works because of the arrow function in render below.
console.log(this.state.message);
}
render() {
return (
<input type="button" value="Log" onClick={() => this.logMessage()} />
);
}
}
同樣,我們也可以在logMessage的實現中國使用箭頭函數。
例如:
class HelloWorld extends React.Component {
// Note that state is a property,
// so no constructor is needed in this case.
state = {
message: 'Hi'
};
logMessage = () => {
// This works because arrow funcs adopt the this binding of the enclosing scope.
console.log(this.state.message);
};
render() {
return (
<input type="button" value="Log" onClick={this.logMessage} />
);
}
}
原文鏈接:https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56