reactjs - 如何从 react-dropzone 中删除文件?

标签 reactjs react-dropzone

希望你能帮我解决这个问题,我正在使用 react-dropzone 中的 useDropzone Hook 而且我不知道如何为每个文件制作一个删除文件按钮。

如何删除单个文件?

这是我的代码:

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;

最佳答案

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

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
};

并在您的 map 中传递数字:acceptedFiles.map(file...应该是 acceptedFiles.map((file, i)....
然后有<button type="button" onClick={() => remove(i)> DeleteButton</button>在哪里 i是数组中文件的编号。

关于reactjs - 如何从 react-dropzone 中删除文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56025690/

相关文章:

javascript - react-dropzone 两次打开文件选择器

reactjs - 在 React Redux 存储中存储文件对象的最佳方式(从 DropZone 上传文件?)

javascript - 为什么使用导入的函数会导致无效的钩子(Hook)错误?

javascript - 即使数据没有改变,react redux useSelector 也会重新渲染

javascript - 如何首先渲染搜索到的项目和所有匹配的项目JavaScript?

javascript - 如何使用refs触发react-dropzone-component的打开功能?

reactjs - react Dropzone 问题 : children is not a function

javascript - 在react-dropzone-uploader的onSubmit方法中访问props

reactjs - 如何使用react-dnd从 Material UI拖放TableHeaderColumn?

javascript - 没有 sibling 时不考虑跨度填充,但在有 sibling 时保留