首页 > 解决方案 > react-dropzone 预览属性丢失

问题描述

几乎尝试了所有方法,但无法正常工作?谁能指出我错过了什么?另外,我查看了其他堆栈溢出帖子,似乎没有什么对我有用。

不知道为什么缺少 file.preview,但它似乎对其他人来说效果很好。是因为使用了组件模型吗?我应该使用功能组件吗?

constructor() {
 super();
  this.onDrop = (files) => {
    console.log(files)
    this.setState({ files })
  };
  this.state = {
    files: []
  };
}

renderPreviewImg(files) {
  console.log(files)
  const img = {
    display: 'block',
    width: 'auto',
    height: '100%'
  };

  const thumb = {
    display: 'inline-flex',
    borderRadius: 2,
    border: '1px solid #eaeaea',
    marginBottom: 8,
    marginRight: 8,
    width: 100,
    height: 100,
    padding: 4,
    boxSizing: 'border-box'
  };

  const thumbInner = {
    display: 'flex',
    minWidth: 0,
    overflow: 'hidden'
  };

  const thumbs = files.map(file => (
    <div style={thumb} key={file.name}>
      <div style={thumbInner}>
        <img
          src={file.preview}
          style={img}
          alt="review"
        />
      </div>
    </div>
  ));
  return thumbs;
}

<Dropzone
  onDrop={this.onDrop}
>
  {({ getRootProps, getInputProps }) => (
    <section className="container">
      <div {...getRootProps({ className: 'dropzone' })}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <aside style={thumbsContainer}>
        {this.renderPreviewImg(this.state.files)}
      </aside>
    </section>
  )}
</Dropzone>

Console.log 文件

缺少预览图像

标签: reactjsreact-dropzone

解决方案


你可以使用这个方法

<img src={URL.createObjectURL(file[0])} />

如果您有多个文件,则遍历文件并为每个文件返回上述语句。

<Dropzone
  onDrop={this.onDrop}
>
  {({ getRootProps, getInputProps }) => (
    <section className="container">
      <div {...getRootProps({ className: 'dropzone' })}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <aside style={thumbsContainer}>
        {this.state.files.map(file=>{
        return <img src={URL.createObjectURL(file[0])} />
        })}
      </aside>
    </section>
  )}
</Dropzone>

推荐阅读