【问题标题】:Can't upload file with useField in formik无法在formik中使用useField上传文件
【发布时间】:2021-03-11 02:26:07
【问题描述】:

我正在尝试使用 formik 上传文件。我有以下代码。

import { Field, ErrorMessage, useField, FieldProps } from "formik";
import { InputHTMLAttributes } from "react";

type FormikImageFieldProps = InputHTMLAttributes<HTMLElement> & {
  label: string;
  name: string;
  component?: string;
};

const FormikImageField: React.FC<FormikImageFieldProps> = ({
  label,
  size: _,
  ...props
}) => {
  const [field, { error, touched }, helper] = useField<FieldProps>(props);

  return (
    <div className="mb-6 pt-3 rounded bg-gray-200">
      <label
        className="block text-gray-700 text-sm font-bold mb-2 ml-3"
        htmlFor={field.name}
      >
        {label}
      </label>
      <Field
        {...field}
        {...props}
        type="file"
        onChange={(e: any) => {
          helper.setValue(e.currentTarget.files[0]);
        }}
        id={field.name}
        className={`bg-gray-200 rounded w-full text-gray-700 focus:outline-none border-b-4 border-gray-300 focus:border-purple-600 transition duration-500 px-3 pb-3 ${
          touched && error ? "border-red-600" : ""
        }`}
      />
      {touched && (
        <ErrorMessage name={field.name}>
          {() => <div className="text-md text-red-600 italic">{error}</div>}
        </ErrorMessage>
      )}
    </div>
  );
};

export default FormikImageField;

现在我的问题是我的 helper.setValue 函数没有设置字段的值。我收到此错误。

Unhandled Runtime Error
InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': 
This input element accepts a filename, which may only be programmatically set to the empty string.

任何想法是什么导致了这个错误。另外,我想遵循这段代码,我不想使用 setFormikField 因为那会导致另一个错误。感谢您的宝贵时间。

【问题讨论】:

    标签: reactjs next.js formik


    【解决方案1】:

    我今天遇到了完全相同的问题。我挣扎了一段时间。我发现你必须传递整个 files 对象。它是FilesList 类型的,它是唯一可读的对象,它存储Files 对象。 应该是:

    helper.setValue(e.currentTarget.files);
    

    helper.setValue([ e.currentTarget.files[0] ]);
    

    同样重要的是,在您的 Formik 表单中,您可以将字段类型设置为 File[],这样可以很容易地将初始值设置为空数组 - []。这种方法还为您的定制提供了很大的灵活性。在调用setValue 方法之前,您可以比较来自event 的文件和Formik 当前存储在field 对象中的文件(来自useForm)。

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 2020-07-20
      • 2021-12-23
      • 2021-06-12
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      相关资源
      最近更新 更多