使用带有自定义输入字段的 React Dropzone Uploader

Use React Dropzone Uploader with custom input field

我可以在 React dropzone 上传器中集成输入吗?基本上,我从输入中获得的文件应该转到 dropzone 上传器。

反应文件放置区:https://github.com/fortana-co/react-dropzone-uploader

<Dropzone
    maxFiles={1}
    accept="image/*"
    getUploadParams={getUploadParams}
    onChangeStatus={handleChangeStatus}
    multiple={false}
    ref={setInputEl}
>
    <input
        ref={setInputEl}
        accept="image/*"
        className={classes.input}
        id="icon-button-file"
        type="file"
        onChange={handleFileChange}
    />
</Dropzone>

可以。

来自the official live examples

// https://github.com/quarklemotion/html5-file-selector
import { getDroppedOrSelectedFiles } from 'html5-file-selector'

const CustomInput = () => {
  const handleSubmit = (files, allFiles) => {
    console.log(files.map(f => f.meta))
    allFiles.forEach(f => f.remove())
  }

  const getFilesFromEvent = e => {
    return new Promise(resolve => {
      getDroppedOrSelectedFiles(e).then(chosenFiles => {
        resolve(chosenFiles.map(f => f.fileObject))
      })
    })
  }

  return (
    <Dropzone
      accept="image/*,audio/*,video/*,.pdf"
      getUploadParams={() => ({ url: 'https://httpbin.org/post' })}
      onSubmit={handleSubmit}
      InputComponent={Input}
      getFilesFromEvent={getFilesFromEvent}
    />
  )
}

其中 Input 是您提供的自定义组件:

const Input = ({ accept, onFiles, files, getFilesFromEvent }) => {
  const text = files.length > 0 ? 'Add more files' : 'Choose files'

  return (
    <label style={{ backgroundColor: '#007bff', color: '#fff', cursor: 'pointer', padding: 15, borderRadius: 3 }}>
      {text}
      <input
        style={{ display: 'none' }}
        type="file"
        accept={accept}
        multiple
        onChange={e => {
          getFilesFromEvent(e).then(chosenFiles => {
            onFiles(chosenFiles)
          })
        }}
      />
    </label>
  )
}

澄清这与您的代码有何不同:您只是将自定义 <input> 添加为 <Dropzone> 的子项。你需要像上面那样做,所以两者都正确 "wired" 在一起。