图像上传验证使用Yup和Formik与单独的组件

huangapple go评论130阅读模式
英文:

Image upload validation with Yup and Formik with a separate component

问题

在我的Next.js应用中,我正在尝试使用Formik和Yup来验证图像上传,通过在组件中传递一个名为 handleOnImageChange 的方法,但我不知道如何使其工作。我还尝试过使用 useFormikContext,但没有成功。有人可以帮助我吗?

以下是与上传组件相关的部分代码:

const validationSchema = yup.object().shape({
    file: yup.mixed().required('请上传一张图片')
});

function handleOnImageChange(event) {
    const file = event.currentTarget.files[0];
    uploadImage(file);
}

<Formik
    onSubmit={handleSubmit}
    initialValues={defaultFormState}
    validationSchema={validationSchema}
>
    {() => (
        <>
            <div>
                <Uploader imageSrc={imageSrc} handleOnImageChange={handleOnImageChange} />
                <ErrorMessage
                    name="file"
                    component={InputError}
                />
            </div>
        </>
    )}
</Formik>

上传组件如下:

const Uploader = ({ handleOnImageChange, imageSrc }) => {
    return (
        <>
            <input id="file" accept=".jpg, .jpeg, .png, .gif, .webp" name="file" type="file" onChange={handleOnImageChange} />
            {imageSrc && (
                <img src={imageSrc} width="200" />
            )}
        </>
    )
}
英文:

In my Nextjs app I'm trying to validate the upload of an image with Formik and Yup by passing a method handleOnImageChange in the component, but I don't know how to get it to work this way.. I also tried with useFormikContext, but without success. Can somebody help me?

 const validationSchema = yup.object().shape({
        file: yup.mixed().required(&#39;Please upload an image&#39;)
    });

 function handleOnImageChange(event) {
      const file = event.currentTarget.files[0];
      uploadImage(file);
  }

&lt;Formik
  onSubmit={handleSubmit}
  initialValues={defaultFormState}
  validationSchema={validationSchema}
&gt;
  {() =&gt; (
    &lt;&gt;
    &lt;div&gt;
     &lt;Uploader imageSrc={imageSrc} handleOnImageChange={handleOnImageChange} /&gt;
     &lt;ErrorMessage
       name=&quot;file&quot;
       component={InputError}
      /&gt;
    &lt;/div&gt;
    &lt;/&gt;
  )}
&lt;/Formik&gt;

With the uploader component:

const Uploader = ({handleOnImageChange, imageSrc}) =&gt; {
  return (
    &lt;&gt;
      &lt;input id=&quot;file&quot; accept=&quot;.jpg, .jpeg, .png, .gif, .webp&quot; name=&quot;file&quot; type=&quot;file&quot; onChange={handleOnImageChange} /&gt;
      {imageSrc &amp;&amp; (
        &lt;img src={imageSrc} width=&quot;200&quot;/&gt;
      )}
    &lt;/&gt;
  )
}

答案1

得分: 1

Here is the translated content:

你必须设置 Formik 的值以进行验证。
在 handleOnImageChange 函数中,你正在调用上传图片的函数,根据我的理解,这个函数会通过 API 端点上传图片,并在响应中返回一个 URL。
将这个函数改为异步等待响应,然后设置 Formik 的状态,让我给你提供一个示例代码。

const validationSchema = yup.object().shape({
  file: yup.mixed().required('请上传图片')
});

async function handleOnImageChange(event, formik) {
  const file = event.currentTarget.files[0];
  let res = await uploadImage(file);
  let url = res.data.url; // 根据你的 API 响应来确定
  formik.setFieldValue("file", url); // "file" 表示你的状态或 Formik 值
}

<Formik
  onSubmit={handleSubmit}
  initialValues={defaultFormState}
  validationSchema={validationSchema}
>
  {(formik) => (
    <>
      <div>
        <Uploader imageSrc={formik.values.file} handleOnImageChange={(e) => handleOnImageChange(e, formik)} />
        <ErrorMessage
          name="file"
          component={InputError}
        />
      </div>
    </>
  )}
</Formik>

你需要检查文件是否为 null 或未定义,以防用户未选择文件并在文件输入中取消选择文件时返回 null 对象。

英文:

you have to set formik values for it to validate.
in the handleOnImageChange function you are calling upload image function which in my understanding is uploading image through an API endpoint and giving you a url in response.
make this function Async await the response then set formik state let me give you a sample code

const validationSchema = yup.object().shape({
        file: yup.mixed().required(&#39;Please upload an image&#39;)
    });

 function async handleOnImageChange(event,formik) {
      const file = event.currentTarget.files[0];
     let res = await uploadImage(file);
let url =res.data.url // depends on your API response
formik.setFieldValue(&quot;file&quot;,url)//&quot;file indicates you state or formik value

  }

&lt;Formik
  onSubmit={handleSubmit}
  initialValues={defaultFormState}
  validationSchema={validationSchema}
&gt;
  {(formik) =&gt; (
    &lt;&gt;
    &lt;div&gt;
     &lt;Uploader imageSrc={formik.values.file} handleOnImageChange={(e)=&gt;handleOnImageChange(e,formik)} /&gt;
     &lt;ErrorMessage
       name=&quot;file&quot;
       component={InputError}
      /&gt;
    &lt;/div&gt;
    &lt;/&gt;
  )}
&lt;/Formik&gt;

you will have to check for null or undefined incase the file is not selected by user and null object is returned when user opens file input and cancels selection of a file.

huangapple
  • 本文由 发表于 2023年5月26日 00:17:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334378.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定