我一直在尝试使用文件阅读器从读取 base64 路径上传图像。首先,我使用了类似的代码,
const reader: FileReader = new FileReader();
reader.onload = function(e: any) {
const imgBase64Path = e.target.result;
this.documentBase64 = imgBase64Path;
this.isImageSaved = true;
this.documents.content = imgBase64Path.toString();
};
Run Code Online (Sandbox Code Playgroud)
在这里,使用“this”在 onload 内部声明的所有变量都没有在外部更新。但是当我改变代码时,
const reader: FileReader = new FileReader();
const this_ = this;
reader.onload = function(e: any) {
const imgBase64Path = e.target.result;
this_.documentBase64 = imgBase64Path;
this_.isImageSaved = true;
this_.documents.content = imgBase64Path.toString();
};
Run Code Online (Sandbox Code Playgroud)
它按预期工作得很好。我无法理解第一个代码的错误是什么以及为什么第二个代码工作正常。我希望有人能帮助我理解这一点......