简体   繁体   English

为输入类型文件键入 onChange 处理程序的正确方法是什么?

[英]What's the correct way to type an onChange handler for input type files?

Almost like Property 'files' does not exist on type 'EventTarget' error in typescript几乎就像属性“文件”在 typescript 类型的“EventTarget”错误中不存在

What's the correct way to type an onChange handler for input type files?为输入类型文件键入 onChange 处理程序的正确方法是什么?

<input
        id="myInput"
        type="file"
        ref={inputEl}
        onChange={onChangeFile}
      />

///
const onChangeFile = (event: React.ChangeEvent<HTMLInputElement>) => {
    event.stopPropagation();
    event.preventDefault();
    const files = Array.from(event.target.files);
    const arr = files.filter((file: any) => imageTypesRegExp.test(file.type));
  };

Which throws errors like:抛出如下错误:

Property 'files' does not exist on type 'EventTarget'.

for the event.target.files and对于event.target.files

Object is of type 'unknown'.

for the file.type对于file.type

Disclaimer: I'm unfamiliar with React/ReactJS, so I'm using only the DOM Event interface .免责声明:我不熟悉 React/ReactJS,所以我只使用 DOM Event接口

  • You need to cast event.target (or event.currentTarget ) to HTMLInputElement .您需要将event.target (或event.currentTarget )转换为HTMLInputElement
  • This is because the Event interface is not generic (so the type of target or currentTarget cannot be specified).这是因为Event接口不是通用的(因此无法指定targetcurrentTarget的类型)。

Like so:像这样:

const onChangeFile = (event: React.ChangeEvent<HTMLInputElement>) => {
    event.stopPropagation();
    event.preventDefault();
    const input = event.target as HTMLInputElement; // <-- here
    const files = Array.from(input.files);
    const arr   = files.filter((file: any) => imageTypesRegExp.test(file.type));
};


As an aside, you don't need this event-handler at all if you want to filter files by MIME type or file-extension, instead use the <input accept="" /> attribute , like so:顺便说一句,如果您想按 MIME 类型或文件扩展名过滤文件,则根本不需要此事件处理程序, 而是使用<input accept="" />属性,如下所示:

  • Only JPEG and PNG images:仅 JPEG 和 PNG 图像:

     <input type="file" accept="image/jpeg, image/png" />
  • Any image:任何图像:

     <input type="file" accept="image/*" />
  • Only video:只有视频:

     <input type="file" accept="video/*" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM