html - 在ts中访问fileReader onload函数中的变量
问题描述
我一直在尝试使用文件阅读器从读取 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();
};
在这里,使用“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();
};
它按预期完美运行。我无法理解第一个代码的错误是什么以及为什么第二个代码可以正常工作。我希望有人能帮助我理解这一点......
解决方案
是范围问题。
您可以使用如下所示的箭头函数(() => {})
将其保持在范围内
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
const imgBase64Path = e.target.result;
this.documentBase64 = imgBase64Path;
this.isImageSaved = true;
this.documents.content = imgBase64Path.toString();
};
推荐阅读
- c# - 坚持如何将用户输入存储到类中并将其显示到 DataGridView
- linux-kernel - bootlin 内核无法从 UBIFS 启动
- java - 出现运行时错误 - ArrayIndextOutofBoundException - 96
- elasticsearch - 模糊匹配百分比
- logging - 可以删除 DB2 中的 LOG 文件吗
- php - 从 html 中抓取某些标签/特定数据之间的任何内容?
- c++ - 如何将 DLL 注入任何进程?
- angular - 访问和修改父组件中的对象
- excel - 如何使 VBA 代码更干净且分数更少?
- fortran - 调用子程序时堆栈溢出