reactjs React Hook表单和输入类型文件

pjngdqdw  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(134)

我正在尝试使用一个输入类型文件与一个React挂钩形式。

import { Controller, useForm } from "react-hook-form";
import {
    Button,
    Form, FormText,
    Label,
    Input,
} from 'reactstrap';

const Test = () => {
  
  const { handleSubmit, control, setValue, formState: { errors }} = useForm();

  // I have other inputs and divs. Just showing the file here
  return (
     <Controller
        name="file"
        control={control}
        render={({ field }) => (
           <Input {...field} type="file" id="file" />
        )}
     />
  );
}

当我提交表单并检查data.file时,它只有:C:\fakepath\myFile.pdf

const submitForm = (data) => {
   console.log(data.file);
}
voase2hg

voase2hg1#

希望还不算太晚。
我自定义react-hook-form的onChange来传递值和名称。

<Controller
      name="profilePath"
      control={control}
      render={({ field }) => (
        <ImgUpload
          src={
            !field.value
              ? userSvg
              : field.value instanceof File
              ? URL.createObjectURL(field.value)
              : field.value
          }
          onChange={(e) =>
            field.onChange({ target: { value: e.target.files[0], name: field.name } })
          }
        />
      )}
    />

相关问题