我想先上传多张图片,先预览,然后提交发送.我遇到过这个:TypeError:无法读取 null 的属性文件".它也只允许我上传一张图片.
- 我创建了 files: [] 作为在提交前安装图像以供审核的方式.
- 尝试创建一个接口 files: File[] = file 然后将其声明为 state 但得到一个不同的错误,即 file 在类型 {} 上不存在
<h3>图像</h3><input type="file" onChange={this.fileSelectedHandler}/></表单>)}}导出默认图片上传
我希望它允许我选择多个图像并将它们存储在数组中,然后再将它们作为批处理发送出去.这甚至是正确的方法吗?非常感谢任何反馈.
解决方案或者,如果您想一张一张地选择图像,您的实现应该可以工作,只需修复 state 声明并使用 e.target.files 来获取所选文件
class ImageUpload extends React.Component {状态 = {文件:[]}fileSelectedHandler = (e) =>{this.setState({ 文件: [...this.state.files, ...e.target.files] })}使成为() {返回 (<表格><div><h2>上传图片</h2></div><h3>图像</h3><input type="file" multiple onChange={this.fileSelectedHandler}/></表单>)}}ReactDOM.render(, document.getElementById('app'))<script src="cdnjs.cloudflare/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="cdnjs.cloudflare/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><div id="app"></div>I would like to upload multiple images first by previewing them then submitting to send them off. I have encountered this: TypeError: Cannot read property 'files' of null. It also only lets me upload just one image.
- I have created files: [] as means to mount the images for review before submitting.
- Tried creating an interface files: File[] = file then declaring it in state but get a different error that file does not exist on type {}
I expect it to allow me to select multiple images and store them in the array before sending them off as a batch. Is this even the right way to do it? Any feedback is greatly appreciated.
解决方案state = { files: [] }
<input type="file" multiple onChange={this.fileSelectedHandler} />
Or if you want to select image one by one, your implementation should work, just fix the state declaration and use e.target.files to get selected file
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="cdnjs.cloudflare/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="cdnjs.cloudflare/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>
更多推荐
使用 React 上传多张图片
发布评论