react-dropzone - 访问通过单击而不是删除添加的文件

react-dropzone - accessing files added by click not drop

我正在使用 react-dropzone 基本示例 (react-dropzone basic)

import React from 'react';
import {useDropzone} from 'react-dropzone';

function Basic(props) {
  const {acceptedFiles, getRootProps, getInputProps} = useDropzone();

  const files = acceptedFiles.map(file => (
    <li key={file.path}>
      {file.path} - {file.size} bytes
    </li>
  ));

  return (
    <section className="container">
      <div {...getRootProps({className: 'dropzone'})}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <aside>
        <h4>Files</h4>
        <ul>{files}</ul>
      </aside>
    </section>
  );
}

<Basic />

这按预期工作,直到我使用单击方法添加文件。使用单击 acceptedFiles 添加文件时不要注册文件(我添加了一个 onChange 处理程序并且 event.target.files 显示了该文件,因此它肯定被添加到整体 FileList 中)。

因此,我无法像显示拖动文件那样在 Files <ul> 中显示通过单击详细信息添加的文件。我假设 fileRejections 也是如此,但我还没有实现它。

我希望我遗漏了一些明显的东西,因为我假设 dropzone 处理拖动和单击行为?

如果可能的话,感谢有人为我指明正确的方向。

上面的代码处理了拖放,但是它只给你最新添加的文件,而不是上传文件的完整列表。

要正确实施它,您可以维护一个状态并向 useDropzone 添加一个 onDrop 函数,您将在其中附加文件并更新状态

function Basic(props) {
  const [files, setFiles] = React.useState([]);
  const onDrop = React.useCallback(acceptedFiles => {
    setFiles(prev => [...prev, ...acceptedFiles]);
  }, []);
  const { getRootProps, getInputProps } = useDropzone({ onDrop });

  const fileList = files.map(file => (
    <li key={file.path}>
      {file.path} - {file.size} bytes
    </li>
  ));

  return (
    <section className="container">
      <div {...getRootProps({ className: "dropzone" })}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <aside>
        <h4>Files</h4>
        <ul>{fileList}</ul>
      </aside>
    </section>
  );
}

Working demo

您的代码没有任何问题。您只需要正确点击 div.

只需为拖放区域添加一些样式,以便拖放和单击时都清楚拖放区域。

working demo is here

export default function Basic(props) {
  const { acceptedFiles, getRootProps, getInputProps } = useDropzone();

  const files = acceptedFiles.map(file => (
    <li key={file.path}>
      {file.path} - {file.size} bytes
    </li>
  ));

  return (
    <section className="container">
      <div
        style={{
          cursor: "pointer",
          background: "gray",
          height: "200px",
          border: "2px dashed blue"
        }}
        {...getRootProps({ className: "dropzone" })}
      >
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <aside>
        <h4>Files</h4>
        <ul>{files}</ul>
      </aside>
    </section>
  );
}