reactjs 当react-hook-form中的必填字段为空时,禁用按钮按下

q9yhzks0  于 2023-03-01  发布在  React
关注(0)|答案(1)|浏览(186)

我想知道如何在下面代码中的Name和State都为空的情况下禁用按钮,换句话说,我想知道如何使按钮只有在name和state都输入的情况下才能按下,而不管email是否为空。

import React from "react";
import { useForm, SubmitHandler } from "react-hook-form";

type FormValues = {
  name: string;
  state: string;
  email: string;
};

export default function App() {
  const { register, handleSubmit } = useForm<FormValues>();
  const onSubmit: SubmitHandler<FormValues> = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("name")} />
      <input {...register("state")} />
      <input type="email" {...register("email")} />

      <input type="submit" />
    </form>
  );
}
vxf3dgd4

vxf3dgd41#

您可以通过检查formState对象的属性isValid来实现这一点。当isValid为false时禁用该按钮,并将register方法中namestaterequired属性设置为true。无论电子邮件输入如何,只要名称或状态为空,该按钮就会以这种方式禁用。
下面是一个工作版本:

import React from "react";
import { useForm, SubmitHandler } from "react-hook-form";

type FormValues = {
  name: string;
  state: string;
  email: string;
};

export default function App() {
  const { register, handleSubmit, formState } = useForm<FormValues>();
  const onSubmit: SubmitHandler<FormValues> = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("name", {required: true})} />
      <input {...register("state", {required: true})} />
      <input type="email"   {...register("email")}/>

      {/* Disable input button if both Name and State are empty */}
      <input type="submit" disabled={!formState.isValid} />
    </form>
  );
}

相关问题