通过react-dropzone和formik在react中上传文件

时间:2019-12-01 18:36:16

标签: reactjs upload formik react-dropzone

我有两个组成部分,首先是Formik形式:

<Formik
  initialValues={{files: []}}
  onSubmit={values => {
  console.log(values)}}>
    {props => (
      <form onSubmit={props.handleSubmit}>
        <UploadComponent/>
        <button type="submit"></button>
      </form>
    )}
</Formik>

第二个是UploadComponent:

const UploadComponent = () => {
  const [files, setFiles] = useState([]);
  const {getRootProps, getInputProps, isDragActive} = useDropzone({
    accept: 'image/*',
    onDrop: acceptedFiles => {
      setFiles(acceptedFiles.map(file => Object.assign(file, {
        preview: URL.createObjectURL(file)
      })))
    }
  })
  return (
    <div>
      <div {...getRootProps({className: 'dropzone'})}>
        <input {...getInputProps()} />
        <p>Drag and drop some files here, or click to select files</p>
      </div>
   </div>
  )

我想将这些文件作为Formik的值,我向UploadComponent添加了一些道具,例如

value={props.values.files}
onChange={props.handleChange}
onBlur={props.handleBlur}
name='files'

我希望在Formik中获得一系列上传的文件。相反,我得到文件(空数组)的初始值。 如何通过react-dropzone获取这些文件并将其传递给formik表单?

1 个答案:

答案 0 :(得分:5)

您应该将Formik道具setFieldValue传递到UploadComponent,并使用它来设置UploadComponent的返回值

Formik表格:

 render={({ values, handleSubmit, setFieldValue }) => {
            return (
              <form onSubmit={handleSubmit}>
                <div className="form-group">
                  <label htmlFor="file">Multiple files upload</label>

                  <UploadComponent setFieldValue={setFieldValue} />//here


                   // list of uploaded files  
                  {values.files &&
                    values.files.map((file, i) => (
                      <li key={i}>
                        {`File:${file.name} Type:${file.type} Size:${
                          file.size
                        } bytes`}{" "}
                      </li>
                    ))}
                </div>
                <button type="submit" className="btn btn-primary">
                  submit
                </button>
              </form>


UploadComponent:

 const UploadComponent = props => {
  const { setFieldValue } = props;
  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    accept: "image/*",
    onDrop: acceptedFiles => {
      setFieldValue("files", acceptedFiles);
    }
  });
  return (
            .
            .
            .


sample codesansbox,希望有帮助