何时在JSX中使用匿名函数 [英] When to use anonymous functions in JSX

查看:154
本文介绍了何时在JSX中使用匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释

一个匿名函数

  <button onClick={() => this.functionNameHere()}></button>

调用如下函数

  <button onClick={this.functionNameHere()}></button>

,以及何时使用其中一种(例如,在不同情况下使用另一种情况).

and also when to use either (such as different scenarios to use one over the other).

推荐答案

第一个示例正确绑定了this的值(lambdas在ES 2015中努力解决的确切问题).

The first example correctly binds the value of this (the exact problem lambdas strive to resolve in ES 2015).

 () => this.functionNameHere()

后者使用this的范围值,可能不是您期望的范围值.例如:

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");
        })
    }

我们需要在此处添加一个lambda:

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
    } )

或手动绑定:

.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

这篇关于何时在JSX中使用匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆