【问题标题】:Image preview using Dropzone extending File type使用 Dropzone 扩展文件类型的图像预览
【发布时间】:2019-09-15 19:21:10
【问题描述】:

想在使用 dropzone 上传之前预览图像。我正在尝试通过调用file.preview 来映射图像,但它在文件类型上不存在。 Dropzone 使用preview?: string 扩展文件类型。我的问题是如何访问扩展类型?如何使用我正在使用的 URL.createObjectURL 显示图像。我是 TypeScript 的新手,无法解决这个问题。任何帮助表示赞赏。

  • 我尝试创建自定义界面,将其导入并将其分配给文件:Pic[] 没有成功。抱怨接受的文件中不存在这些属性。我明白那个。也许我必须声明函数中的内容是什么?不知道。
export interface Pic {
  picId: string
  name: string
  preview: string
}
  • 我在 onDrop 函数中为 Object.assigned 一个预览 URL。它会继续,但仍然无法通过 files.preview 访问它。

  • 我尝试使用构造函数来获取扩展类型,但完全迷失在我想要实现的目标中。

import * as React from "react"
import styles from "../../styles.scss"
import Dropzone from "react-dropzone"

class ImageUpload extends React.Component {
  state = {
    files: []
  }

  handleOnDrop = (files: File[]) => {
    files.map(file => Object.assign(file, {
      preview: URL.createObjectURL(file)
    }))
    this.setState({ files: [...this.state.files, ...files] })
    console.log(files)
  }

  render() {
    const files = this.state.files.map((file: File) => (
      console.log(file),
      (
        <li key={file.name}>
          {file.preview}
        </li>
      )
    ))

    return (
      <form>
        <div>
          <h2>Upload images</h2>
        </div>
        <Dropzone onDrop={this.handleOnDrop} accept="image/*" />
        <ul>{files}</ul>
      </form>
    )
  }
}

export default ImageUpload

预期结果:file.preview URL 有效,我可以将其用作背景图像。 实际结果:file 类型上不存在 file.preview。

【问题讨论】:

    标签: reactjs typescript dropzone.js


    【解决方案1】:

    我的问题是如何访问扩展类型?

    通过从类型定义中导入接口:

    import Dropzone, { FileWithPreview } from "react-dropzone"

    除了那个问题。 Array.map 函数返回一个新数组。目前您只映射文件数组,但您没有对新数组做任何事情。您可能希望使用该新数组来设置您的状态:

    const filesWithPreviews: FileWithPreview[] = files.map(
      // Add the preview property to each file element
    );
    
    this.setState({ files: [...this.state.files, ...filesWithPreviews] });
    

    你是 TypeScript 的新手。你应该设置一个接口来匹配你的状态。

    interface IState {
      files: FileWithPreview[];
    }
    
    class ImageUpload extends React.Component<{}, IState> {
    }
    

    通过这种方式,TypeScript 让您知道您正在尝试将不正确类型的元素存储到您想要的状态(就像现在在您的 dropHandle 函数中发生的那样)。在映射数组时,您不必在渲染函数中明确说明文件是 File

    【讨论】:

    • 我最终模仿了我在 dropzone @type 中看到的内容。我创建了interface ImageFile extends file { preview?: string } 并将参数更改为ImageFile。当我扩展接口时,我遇到了很多问题,即类型上不存在东西。不过感谢您的帮助!
    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 2016-11-15
    • 2015-05-29
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多