3

我正在为我的 React 项目编写一些 JavaScript 代码。代码加载一系列图像,然后使用每个图像的尺寸更新状态。问题是当我调用onload函数时,this关键字是指附加到onload. 这意味着我不能再通过this.props. 有没有办法将道具传递给函数?

这是我的代码:

for (var i = 0; i < a; i++) {

  var path = i + ".jpg";
  imgArray[i].index = i;

  imgArray[i].onload = function() {
    this.props.actions.updateImage(this.index, this.width, this.height);
  }

  imgArray[i].src = path;
}

我目前收到一个错误,this.props未定义,因为this在函数中引用 imgArray[i],而不是全局上下文。

4

2 回答 2

2

一个简单的解决方案可能只是将上下文或道具保存到变量中并使用它们:

const { props } = this;

// ...

imgArray[i].onload = function() {
  props.actions.updateImage(this.index, this.width, this.height);
}

如果您发现其他上下文更具可读性,您也可以保存:

const ctx = this;

// ...

imgArray[i].onload = function() {
  ctx.props.actions.updateImage(this.index, this.width, this.height);
}
于 2018-01-11T01:18:08.333 回答
1

最好的办法是使用一个变量来捕获道具,该变量包含对您通过闭包访问的外部“this”的引用:

// This line here, now inside the function, use 'self' to refer to outer context
let self = this;
for (var i = 0; i < a; i++) {

  var path = i + ".jpg";
  imgArray[i].index = i;

  imgArray[i].onload = function() {
    // note call to self.props instead of this.props:
    self.props.actions.updateImage(this.index, this.width, this.height);
  }

  imgArray[i].src = path;
}
于 2018-01-11T01:19:40.770 回答