You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic v3+TypeScript存文件URL到数组报错:HTMLElement无name_array属性

解决Ionic v3/TypeScript中图片加载回调里数组访问的错误

这个问题的核心是this指向的问题——在img.onload的普通函数回调里,this指向的是当前的imgDOM元素(也就是HTMLElement类型),而不是你的Ionic组件实例,所以才会抛出“The 'name_array' property does not exist on the 'HTMLElement' type”的错误。

下面给你几种可行的解决方法:

方法1:使用箭头函数(推荐)

箭头函数不会绑定自己的this,它会继承外层作用域的this(也就是你的组件实例),这样就能正常访问name_array了:

let img = new Image();
img.src = file_url;
img.onload = () => {
  if (img.width === img.height * 2) {
    this.name_array.push({ id: 1, url: file_url });
  }
};

方法2:提前保存组件的this引用

你可以在回调函数外把组件的this保存到一个变量(比如self或者that),然后在回调里用这个变量访问数组:

const self = this; // 保存组件实例的this
let img = new Image();
img.src = file_url;
img.onload = function () {
  if (img.width === img.height * 2) {
    self.name_array.push({ id: 1, url: file_url });
  }
};

方法3:用bind()绑定this

通过bind()方法把回调函数的this强制绑定到组件实例上:

let img = new Image();
img.src = file_url;
img.onload = function () {
  if (img.width === img.height * 2) {
    this.name_array.push({ id: 1, url: file_url });
  }
}.bind(this); // 绑定组件的this到回调函数

额外注意点

请确保你已经在组件类里正确声明并初始化了name_array,比如:

export class YourPage {
  // 声明并初始化数组
  name_array: Array<{ id: number, url: string }> = [];

  // 你的方法(比如处理图片的方法)
  processImage(file_url: string) {
    // 上面的代码放在这里
  }
}

内容的提问来源于stack exchange,提问作者Sano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:16:38