【问题标题】:Upload image one at a time with preview issue - React Drop zone一次上传一张图片,有预览问题 - React Drop zone
【发布时间】:2020-08-14 09:52:47
【问题描述】:
  const [files, setFiles] = useState([]);

  const onDrop = useCallback((acceptedFiles) => {
    // Do something with the files
    setFiles(
      acceptedFiles.map((file: File) =>
        Object.assign(file, {
          preview: URL.createObjectURL(file),
        })
      )
    );
  }, []);
  const { getRootProps, getInputProps } = useDropzone({
    onDrop,
    accept: 'image/*',
    multiple: false,
  });


  const thumbs = files.map((file: { [key: string]: string }) => (
    <div className={classes.imagePreview} key={file.name}>
      <img className={classes.image} src={file.preview} alt={file.name} />
    </div>
  ));

  useEffect(() => {
    // Make sure to revoke the data uris to avoid memory leaks
    files.forEach((file: { [key: string]: string }) =>
      URL.revokeObjectURL(file.preview)
    );
  }, [files]);

我的 HTML

 <div className={classes.imageContainer}>
          {thumbs}
          <div className={classes.borderBox} {...getRootProps()}>
            <input {...getInputProps()} />
            <div>
              <AddIcon />
            </div>
          </div>
        </div>

我正在尝试通过 dropzone 一次上传一张,但是我的图片被第二张替换了。

【问题讨论】:

    标签: react-hooks dropzone react-dropzone


    【解决方案1】:

    通过附加到状态来修复它

      const onDrop = useCallback(
        (acceptedFiles) => {
          // Process files
          const oneFile = get(acceptedFiles, '[0]', []);
          Object.assign(oneFile, { preview: URL.createObjectURL(oneFile) });
          setFiles([oneFile, ...files]);
        },
        [files]
      );
    

    【讨论】:

    • 嗨@vini,我刚刚安装了 react-dropzone 最新版本 11.0.3,我看不到那里的样式(css)。你能告诉我我做错了什么吗?我想运行你的代码
    • @UsmanI 您需要将样式导入到您的 js 中,否则将无法正常工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2014-01-13
    • 1970-01-01
    • 2015-10-09
    • 2021-08-11
    相关资源
    最近更新 更多