React:不使用&;this&;的最干净的访问组件的方式

React: Cleanest way of accessing component without using "this"

本文关键字:方式 组件 访问 this React      更新时间:2023-09-26

我需要访问一个嵌套在一个handler函数中的函数中的React组件。

当在嵌套函数中this不提供对组件的引用时

所以我显式地声明它而不是通常的this.setState(...)

是否有比我下面的代码更干净的方法?

React.createClass({
    uploadImage : function() {
    ...
    var componentReference = this
    xhrRequest.onreadystatechange = function()
        {if(request.readyState==4) {
        componentReference.setState({uploadStatus: request.status});
        }
    }

这就是JavaScript的工作方式:

  1. 你必须保持一个引用,无论你想在一个不同的上下文中调用的函数访问(就像你实现它与你的变量)…

  • …绑定this在函数调用时指向的位置。没有必要使用库(如lodash),因为ECMAScript 5.1内置了它,你可以在任何最近的浏览器(Chrome 7+, Firefox 4+, IE 9+, Safari 5.1+)中使用它,参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  • 如果你需要支持旧的浏览器,你可以自己实现一个bind函数,参见例如Underscore.js的Function.prototype.bind实现:http://underscorejs.org/#bind

    最惯用的方法是使用本机.bind()方法,不需要库:

    React.createClass({
        uploadImage : function() {
            // ...
            xhrRequest.onreadystatechange = function() {
                if(request.readyState == 4) {
                    this.setState({ uploadStatus: request.status });
                }
            }.bind(this)
            // ...
        }
    })
    

    .bind(this).onreadystatechange闭包中设置this 的上下文。这有点像将作用域传递给内部函数。

    如果你正在使用lodash,你可以这样做:

    xhrRequest.onreadystatechange = _.bind(function () {
        if ( request.readyState == 4 ) {
            this.setState({ uploadStatus: request.status });
        }
    }, this);
    

    你可以简单地在普通的旧JS中使用Function绑定方法,如Function () {}.bind(this),然后函数中的"this"将成为你的React组件。

    你可以在这里看到bind()的定义https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

    你可以把onreadystatechange处理程序放在"类"本身,从React的自动绑定中获利。

    您也可以保留对setState的引用,但我不确定这是否也是自动绑定的。试试吧。

    最后但并非最不重要的是,由于您可能会使用转译器,因此您可以使用ES6箭头函数。箭头函数使用this(词法this)的" outer "值