【问题标题】:Uploading files in react by react-dropzone and formik通过 react-dropzone 和 formik 在 react 中上传文件
【发布时间】:2019-12-01 18:36:16
【问题描述】:

我有两个组件,第一个是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表单?

【问题讨论】:

  • 你应该使用 setFieldValue 将你的数组传递给 Formik: (field: string, value: any, shouldValidate?: boolean),你可以试试这个吗? jaredpalmer.com/formik/docs/api/formik
  • @OzanManav 我需要承认我不知道如何正确实施它。我的意思是在某些情况下它应该类似于onClick={e =&gt; {props.setFieldValue('example', e.target.value)。但我不知道在这种情况下应该使用哪个事件(将图像放入输入文件)
  • 试过onChange={e =&gt; (props.setFieldValue('files', e.currentTarget.value ))},不行
  • 你能创建codesandbox让我帮你解决吗?
  • 利用 Formik 中的 setFieldValue 方法,该方法将为您的特定字段设置值,然后使用 on change 或 submit handler 从该字段获取值

标签: reactjs upload formik react-dropzone


【解决方案1】:

您应该将 Formik props 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>


上传组件:

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


sample codesansbox,希望对您有所帮助

【讨论】:

  • 是否有保留以前文件的选项?通常你会做setFiles((files) =&gt; [...files, ...acceptedFiles])。否则之前的数据总是被删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
  • 2019-01-29
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多