首页 > 解决方案 > 如何从 react-dropzone 中删除文件?

问题描述

希望你能帮我解决这个问题,我正在使用react-dropzone中的 useDropzone 挂钩,但我不知道如何为每个文件创建一个删除文件按钮。

如何删除单个文件?

这是我的代码:

function DragFile(props) {
  const { acceptedFiles, rejectedFiles, getRootProps, getInputProps } = useDropzone({
    accept: 'image/jpeg, image/png, .pdf',
    maxSize: 3000000,
    multiple: true
  });

  const acceptedFilesItems = acceptedFiles.map(file => (
    <Col xs={12} md={4} key={file.path} className="card-file">
      <div className="file-extension">{file.path.substring(file.path.indexOf('.') + 1)}</div>
      <span>{file.path.substring(0, file.path.indexOf('.'))} <small>{(file.size / 1000).toFixed(2)} Kb</small></span>
      <button className="delete">DeleteButton</button>
    </Col>
  ));

  const rejectedFilesItems = rejectedFiles.map(file => (
    <li key={file.path}>
      {file.path.substring(0, file.path.indexOf('.'))} - {file.size / 1000} Kb
    </li>
  ));

  return (
    <div>
      <div {...getRootProps({ className: 'dropzone drag-n-drop' })}>
        <input id="file-claim" {...getInputProps()} />
        <img src={uploadSrc} alt="Subir archivo" />
        <p>Drag files here (PDF, JPG, PNG).</p>
      </div>
      <Row className="accepted-files">
        {acceptedFilesItems}
      </Row>
    </div>
  );
}

export default DragFile;

标签: reactjsreact-dropzone

解决方案


您可能已经完成了这项工作,但您只需要将其附加到点击处理程序:

const remove = file => {
  const newFiles = [...files];     // make a var for the new array
  newFiles.splice(file, 1);        // remove the file from the array
  setFiles(newFiles);              // update the state
};

并在你的地图中传递数字:acceptedFiles.map(file...应该是acceptedFiles.map((file, i)....

然后有<button type="button" onClick={() => remove(i)> DeleteButton</button>wherei是数组中文件的编号。


推荐阅读