我正在为我的 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],而不是全局上下文。