【发布时间】:2017-07-08 10:23:48
【问题描述】:
谁能解释一下
一个匿名函数
<button onClick={() => this.functionNameHere()}></button>
和
如下调用函数
<button onClick={this.functionNameHere()}></button>
以及何时使用其中之一(例如在不同的场景中使用一个而不是另一个)。
【问题讨论】:
谁能解释一下
一个匿名函数
<button onClick={() => this.functionNameHere()}></button>
和
如下调用函数
<button onClick={this.functionNameHere()}></button>
以及何时使用其中之一(例如在不同的场景中使用一个而不是另一个)。
【问题讨论】:
第一个示例正确绑定了this 的值(正是 lambdas 努力在 ES 2015 中解决的问题)。
() => this.functionNameHere()
后者使用this 的范围值,这可能不是您所期望的。例如:
export default class Album extends React.Component {
constructor(props) {
super(props);
}
componentDidMount () {
console.log(this.props.route.appState.tracks); // `this` is working
axios({
method: 'get',
url: '/api/album/' + this.props.params.id + '/' + 'tracks/',
headers: {
'Authorization': 'JWT ' + sessionStorage.getItem('token')
}
}).then(function (response) {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
}).catch(function (response) {
console.error(response);
//sweetAlert("Oops!", response.data, "error");
})
}
我们需要在这里加入一个 lambda:
.then( (response) => {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
} )
或手动绑定:
.then(function (response) {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
}.bind(this) )
示例被盗取自:React this is undefined
【讨论】:
在ES6中,第一种情况“this”指的是被调用函数所属的Component。 <button onClick={() => this.functionNameHere()}></button> 等价于<button onClick={this.functionNameHere.bind(this)}></button>。
另一方面,在<button onClick={this.functionNameHere()}></button> 中,“this”指的是按钮本身。
我来自 Python,但我仍然对 javascript 上下文有点困惑。查看此视频了解更多信息:https://www.youtube.com/watch?v=SBwoFkRjZvE&index=4&list=PLoYCgNOIyGABI011EYc-avPOsk1YsMUe_
【讨论】: