When to use anonymous functions in JSX

主宰稳场 提交于 2020-01-06 21:13:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!