【问题标题】:How to remove file from react-dropzone?如何从 react-dropzone 中删除文件?
【发布时间】:2019-05-07 15:14:23
【问题描述】:

希望您能帮我解决这个问题,我正在使用来自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;

【问题讨论】:

    标签: reactjs react-dropzone


    【解决方案1】:

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

    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)....

    然后有&lt;button type="button" onClick={() =&gt; remove(i)&gt; DeleteButton&lt;/button&gt;,其中i 是数组中文件的编号。

    【讨论】:

    • newFiles 变量的展开运算符从何而来?我尝试使用接受文件,但无法正常工作。有什么建议吗?
    • setFiles 的定义是什么?它是 useDropZone 钩子的一部分吗?
    • 你的代码应该像这样更正&lt;button type="button" onClick={() =&gt; remove(i) }&gt;
    【解决方案2】:

    希望对你有帮助:

    import React, { useState, useEffect, useCallback } from 'react'
    import { useDropzone } from 'react-dropzone'
    
    const CreateFileUpload = () => {
      const onDrop = useCallback(acceptedFiles => {
        // Do something with the files
      }, [])
      const { getRootProps, getInputProps, isDragActive, acceptedFiles } = useDropzone({ onDrop, accept: '.png, .jpeg' })
      const files = acceptedFiles.map((file, i) => (
        <li key={file.path} className="selected-file-item">
          {file.path}  <i className="fa fa-trash text-red" onClick={() => remove(i)}></i>
        </li>
      ));
      const remove = file => {
        const newFiles = [...files];     // make a var for the new array
        acceptedFiles.splice(file, 1);        // remove the file from the array
      };
      return (
        <div>
          <div {...getRootProps()} className="dropzone-main">
            <div
              className="ntc-start-files-dropzone"
              aria-disabled="false"
            >
            </div>
            <button className="add-button" type="button">
              <i className="fa fa-plus"></i>
            </button>
            <h3 className="upload-title">
              <span></span>
            </h3>
            <input
              type="file"
              multiple=""
              autocomplete="off"
              className="inp-file"
              // onChange={uploadFile}
              multiple
              {...getInputProps()}
            />
            {isDragActive ?
              <div></div>
              :
              <div>
                <p>  Upload files  </p>
              </div>
            }
          </div>
          <aside>
            {files.length > 0 ? <h5>Selected Files</h5> : <h5></h5>}
            <ul>{files}</ul>
          </aside>
        </div>
      )
    }
    export default CreateFileUpload
    

    【讨论】:

    • 在示例中您不使用newFiles
    【解决方案3】:

    当您删除文件时,将该数据添加到您的状态,它应该允许您访问数据,以便您可以删除。

    大致:

    onDrop = (files) => {
      // use a foreach loop get the file name using Object.keys
      // setState with the file names
      // whatever else you need to do to process the file
    }
    
    handleDelete = () => {
      // use the file names from your state to delete the files
    }
    

    在那里的某个地方,你必须将它与 jsx 结合起来。您还需要使其与您发送到服务器的任何内容保持同步。这一切都应该通过您的组件状态来完成。

    【讨论】:

      【解决方案4】:

      让我添加这段代码,因为这里的其他答案我不清楚:

      您需要创建自己的 myFiles 状态并使用 onDrop 函数对其进行更新,然后使用您的 remove 函数从本地状态中删除该文件。

      import React, { useState, useCallback } from "react"
      import { useDropzone } from "react-dropzone"
      
      function Basic(props) {
        const [myFiles, setMyFiles] = useState([])
      
        const onDrop = useCallback(acceptedFiles => {
          setMyFiles([...myFiles, ...acceptedFiles])
        }, [myFiles])
      
        const { getRootProps, getInputProps } = useDropzone({
          onDrop,
        })
      
        const removeFile = file => () => {
          const newFiles = [...myFiles]
          newFiles.splice(newFiles.indexOf(file), 1)
          setMyFiles(newFiles)
        }
      
        const removeAll = () => {
          setMyFiles([])
        }
      
        const files = myFiles.map(file => (
          <li key={file.path}>
            {file.path} - {file.size} bytes{" "}
            <button onClick={removeFile(file)}>Remove File</button>
          </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>
            {files.length > 0 && <button onClick={removeAll}>Remove All</button>}
          </section>
        )
      }
      
      export default Basic
      

      【讨论】:

        猜你喜欢
        • 2020-09-13
        • 1970-01-01
        • 2017-02-12
        • 2022-09-29
        • 2017-03-21
        • 2017-08-21
        • 2019-08-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多