【问题标题】:How to get image dimensions from <input type="file"> with React & TypeScript before upload?如何在上传之前使用 React 和 TypeScript 从 <input type="file"> 获取图像尺寸?
【发布时间】:2021-04-17 14:29:39
【问题描述】:

我正在尝试在使用 React 和 TypeScript 上传之前获取图像尺寸。

这是我的代码:

<input
  //...
  type="file"
  accept="image/png, image/jpeg"
  onChange={(e) => {
    const ev = e.currentTarget.files;
    if (ev) {
      if (ev.length === 0) {
        return;
      }
      var img: HTMLImageElement;
      img = document.createElement("img");

      img.onload = function (event) {
        console.log({ width: event.width, height: event.height });
      };

      img.src = URL.createObjectURL(eventFiles[0]);
    }
    //...
  }}
/>

但我收到这种类型的错误:

“事件”类型上不存在属性“宽度”.ts(2339)

事件的正确类型是什么,这是正确的方式吗?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您的代码中的错误是源对象不是event,而是img 本身。您可以尝试以下更改

    img.onload = function () {
                  console.log({ width: img.width, height: img.height });
                };
    

    【讨论】:

    • 感谢您的回答。它工作得很好。
    猜你喜欢
    • 2014-10-29
    • 2020-01-15
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2011-10-21
    • 2016-12-29
    • 2012-05-11
    • 2012-02-11
    相关资源
    最近更新 更多