我正在“重新调整”文件输入,但无法迭代选定的文件。
private onInputChanged = (e: React.FormEvent<HTMLInputElement>): void => {
let files: FileList | null = e.currentTarget.files;
files.map( file => console.log("Do something with " + file.name));
}
<input
type="file"
onChange={this.onInputChanged}
/>
这是我的问题的一个简单示例。 FileList 不能与 .map(... 一起使用,也不能与 .forEach(...
如何完成选定文件的迭代?
错误:“FileList”类型上不存在属性“map”
FileList https://developer.mozilla.org/en-US/docs/Web/API/FileList是一个类似数组的对象,具有length
属性和索引值,但它缺少数组方法,例如map。通过 ES6 你可以使用spread https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax or 数组#来自 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from将其转换为真正的数组。在 ES5 中你可以调用数组#切片 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice转换为数组,或者call https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/callFileList 上的方法。
Note:如果 Array#from 导致打字稿 |数组.from |错误 TS2339:类型“ArrayConstructor”上不存在属性“from”错误,修改默认值target(es3) 到 ES6 -"target": "ES6"
- 在里面编译器选项 https://www.typescriptlang.org/docs/handbook/compiler-options.html of the “tsconfig.json”,或在命令行中使用--target ES6。
数组.来自演示:
const onInputChanged = (e) => {
const files = e.currentTarget.files;
Array.from(files).forEach(file => console.log("Do something with " + file.name));
}
<input
type="file"
onChange="onInputChanged(event)"
/>
调用每个演示:
const onInputChanged = (e) => {
const files = e.currentTarget.files;
[].forEach.call(files, file => console.log("Do something with " + file.name));
}
<input
type="file"
onChange="onInputChanged(event)"
/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)