React.js中的默认函数

时间:2017-09-10 12:27:18

标签: javascript reactjs

我有一个这样的代码片段,有效:

android:background="@android:color/transparent"

上面,class Button extends React.Component { state = { counter : 0 } handleClick = () => { this.setState({ counter: this.state.counter+1 }) } render() { return ( <button onClick={this.handleClick}> {this.state.counter} </button> ) } } 函数是箭头1。 下面,我尝试使用默认功能(来自ES5):

handleClick

第二个代码段无法正常工作的问题在于功能的写作方式?或者别的地方? React js不处理默认函数吗?

4 个答案:

答案 0 :(得分:2)

当你这样写:

class Example {
  handleClick = (e) => {
    this.doStuff(e);
  }
}
巴贝尔正在将其描述为:

var Example = function Example() {
  var _this = this;

  this.handleClick = function (e) {
    return _this.doStuff(e);
  };
};

方法handleClick可以访问对象的实例,因为构造函数将实例存储在变量_this中,并且该方法形成一个闭包,其中_this可用于其中词汇环境。它使用_this代替关键字this,因为当事件监听器调用时不知道原始对象时,this将具有值window (或undefined如果启用了严格模式。)


<小时/> 现在,当您使用常规function而不是箭头函数时,如下所示:

class Test {
  handle = function (e) {
     return this.doStuff(e);
  }
}

它被转化为这样的事情:

var Test = function Test() {
  this.handle = function (e) {
    return this.doStuff(e);
  };
};

正如您所看到的,它现在尝试通过关键字this来访问实例,该关键字在从事件侦听器调用方法时不会成为对象实例,因此它不会按预期工作。


如果你是一个像我这样的梦想家,你想要思考一个“等级”属性转变的世界&#34;是实际规范的一部分,我们原生使用ES2xxx,您可以将箭头功能版本视为与以下内容等效:

class Example {
  constructor() {
    this.handleClick = (e) => {
      this.doStuff(e);
    }
  }
}

你可以在这里看到它在构造函数中创建了一个箭头函数,并且因为箭头函数从周围的范围中获取它们的上下文(即this的值) ,这里的范围是构造函数本身,this将具有适当的值,无论方法在何处调用。

答案 1 :(得分:1)

在ES6中,this在箭头功能中使用时具有不同的含义。 this函数中的arrow引用class的实例,其中this通常function引用function的实例class 1}}本身而不是this。这在ES6规范中被称为词汇this.state.counter+1

因此,在您的情况下,正常function中的undefined将为function。如果您必须使用class Button extends React.Component { state = { counter : 0 } self = this handleClick = function() { self.setState({ counter: self.state.counter+1 }) } ... } ReactDOM.render(<Button/>, mountNode) , 那么我想你应该这样做:

four=xr.DataArray(np.ones((1,4,5)), coords=[['four'],pd.date_range('1/1/2000', periods=4),['a', 'b', 'c', 'd','e']], 
                  dims=['items','major_axis','minor_axis'])

pxc=xr.concat([px,four],dim='items')

IMO,但绑定更好

答案 2 :(得分:0)

您需要将方法绑定到您的类:

onClick={this.handleClick.bind(this)}

答案 3 :(得分:-2)

在您的ES5代码中替换以下

onClick={this.handleClick}

onClick={this.handleClick()}
相关问题