简体   繁体   English

React.js:HTML输入传递文件数组onChange

[英]React.js: HTML Input to pass array of Files onChange

I have a function that accepts an array of Files. 我有一个接受文件数组的函数。

I want to reuse this function, without having to change it, for accepting files from an HTML5 input. 我想重用此功能,而不必更改它,以接受来自HTML5输入的文件。

Here is my input: 这是我的输入:

 render() {
   return (
    <div>
      <form>
        <input className="fileInput" 
          type="file" 
          onChange={this.onUpload.bind(this)} />
     </form>
   </div> 
 )}

Here is the function that I want to call: 这是我要调用的函数:

 onUpload(arrayOfFiles) {
   // do something with files
 }

The problem is, that when I call onUpload from my input, it does not pass in an array of Files. 问题是,当我从输入中调用onUpload时,它没有传递文件数组。 In order to access the files, I would have to do something like this in my onUpload function: 为了访问文件,我必须在onUpload函数中执行以下操作:

 files = arrayOfFiles.target.files;

How can I pass the array of Files itself to my onUpload function? 如何将文件数组本身传递给onUpload函数?

This won't work: 这行不通:

<form>
  <input className="fileInput" 
   type="file" 
   onChange={this.onUpload.bind(this.target.files)} />
</form>

I get the error "Cannot read property 'files' of undefined" 我收到错误消息“无法读取未定义的属性'文件'”

Changing the input to the following does the trick: 将输入更改为以下内容可以达到目的:

<input className="fileInput" 
   type="file" 
  onChange={(e) => this.onUpload(e.target.files)} />

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

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