我想先通过预览来上传多张图像,然后提交以发送它们。我遇到过这样的情况:TypeError: Cannot read property 'files' of null
。它还只允许我上传一张图像。
- 我创造了
files: []
作为在提交之前安装图像以供审核的方法。
- 尝试创建一个界面
files: File[] = file
然后在状态中声明它但得到一个不同的错误file does not exist on type {}
import * as React from "react"
class ImageUpload extends React.Component {
state: {
files: []
}
fileSelectedHandler = (file: any) => {
let addedFiles = this.state.files.concat(file)
this.setState({ files: addedFiles })
console.log("upload file " + file.name)
}
render() {
return (
< form >
<div>
<h2>Upload images</h2>
</div>
<h3>Images</h3>
<input type="file" onChange={this.fileSelectedHandler} />
</form>
)
}
}
export default ImageUpload
我希望它允许我选择多个图像并将它们存储在数组中,然后再将它们批量发送。这是正确的做法吗?非常感谢任何反馈。
- 为了修复错误
TypeError: Cannot read property 'files' of null.
你需要改变state
宣言
state = {
files: []
}
- 如果您想有机会选择多个文件,您可以使用
multiple
option
<input type="file" multiple onChange={this.fileSelectedHandler} />
或者,如果您想一张一张地选择图像,您的实现应该可以工作,只需修复state
声明和使用e.target.files
获取选定的文件
class ImageUpload extends React.Component {
state = {
files: []
}
fileSelectedHandler = (e) => {
this.setState({ files: [...this.state.files, ...e.target.files] })
}
render() {
return (
<form>
<div><h2>Upload images</h2></div>
<h3>Images</h3>
<input type="file" multiple onChange={this.fileSelectedHandler} />
</form>
)
}
}
ReactDOM.render(<ImageUpload />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)