使用 React 上传多个图像

Pro*_*zak 5 typescript reactjs

我想先通过预览来上传多张图像,然后提交以发送它们。我就遇到过这样的情况: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

Run Code Online (Sandbox Code Playgroud)

我希望它允许我选择多个图像并将它们存储在数组中,然后再将它们批量发送。这是正确的做法吗?非常感谢任何反馈。

Ale*_* T. 7

  1. 为了修复错误,TypeError: Cannot read property 'files' of null.您需要更改state声明
state = {
   files: []
}
Run Code Online (Sandbox Code Playgroud)
  1. 如果您想有机会选择多个文件,您可以使用multiple选项
<input type="file" multiple onChange={this.fileSelectedHandler} />
Run Code Online (Sandbox Code Playgroud)

或者,如果您想一张一张地选择图像,您的实现应该可以工作,只需修复state声明并使用e.target.files即可获取选定的文件

state = {
   files: []
}
Run Code Online (Sandbox Code Playgroud)
<input type="file" multiple onChange={this.fileSelectedHandler} />
Run Code Online (Sandbox Code Playgroud)