问题
can someone explain the difference between
an anonymous function
<button onClick={() => this.functionNameHere()}></button>
and
calling the function like below
<button onClick={this.functionNameHere()}></button>
and also when to use either (such as different scenarios to use one over the other).
回答1:
In ES6, with the first scenario "this" refers to the Component where the function called belongs to. <button onClick={() => this.functionNameHere()}></button>
is equivalent to <button onClick={this.functionNameHere.bind(this)}></button>
.
On the other hand, in <button onClick={this.functionNameHere()}></button>
"this" refers to the button itself.
I came from Python and I'm still a bit confuded about javascript context. Check this video for further info: https://www.youtube.com/watch?v=SBwoFkRjZvE&index=4&list=PLoYCgNOIyGABI011EYc-avPOsk1YsMUe_
回答2:
The first example correctly binds the value of this
(the exact problem lambdas strive to resolve in ES 2015).
() => this.functionNameHere()
The latter uses the scoped-value of this
which might not be what you expect it to be. For example:
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");
})
}
We would need to sub in a lambda here:
.then( (response) => {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
} )
or bind manually:
.then(function (response) {
console.log(response.data);
this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
}.bind(this) )
Examples stolen from: React this is undefined
来源:https://stackoverflow.com/questions/42322553/when-to-use-anonymous-functions-in-jsx