如何动态使用表单标签之外的按钮来提交表单

问题描述 投票:0回答:1

我有一个多步骤表单,其中有一个“下一步”按钮,可引导您完成不同的步骤。在最后一页上,它变为连接到表单的“提交”按钮。

我在按钮上动态设置

type
form
属性,理论上应该会触发表单的 onSubmit 操作。但点击“提交”并不会触发
onSubmit
功能。

是否可以在

<form>
标签之外有一个按钮像这样动态提交表单?

具体按钮为:

<button
  className="btn text-white btn-neutral w-24"
  onClick={
    step < 3
      ? () => {
          handleNext();
        }
      : undefined
  }
  type={step >= 3 ? "submit" : undefined}
  form={step >= 3 ? "visa-form" : undefined}
>
  {step >= 3 ? "Submit" : "Next"}
</button>

整个文件代码如下:

"use client";

import ...;

export default function IntakeForm() {
  const [step, setStep] = useState(0);

  const {
    register,
    unregister,
    handleSubmit,
    formState: { errors },
    trigger,
    watch,
  } = useForm<VisaRecommendationFormModel>({
    resolver: zodResolver(VisaRecommendationFormSchema),
  });

  const onSubmit = (data: VisaRecommendationFormModel) => {
    console.log("Form submitted with data:", data);
    // Add your form submission logic here
  };

  const handlePrevious = () => {
    setStep(step - 1);
  };

  const handleNext = async () => {
    console.log("handling next");
    const isValid = await trigger(["fields", "to", "validate"]);

    if (isValid) {
      const nextStep = step + 1;
      setStep(nextStep);
    }
  };

  return (
    <div className="relative flex flex-col justify-center items-center pt-14 gap-10">
      <form
        className="border-2 rounded-xl p-14 h-[448px] w-[660px] flex flex-col items-center justify-center"
        onSubmit={handleSubmit(onSubmit)}
        id="visa-form"
      >
        {step === 0 && <CurrentLocationInput register={register} />}
        {step === 1 && <FamilyInformationInput register={register}/>}
        {step === 2 && <CareerInformationInput register={register} />}
        {step === 3 && <PersonalInformationInput register={register} />}
      </form>
      <div className="flex flex-row gap-x-96">
        <button
          className={`btn text-white btn-neutral w-24 ${
            step <= 0 ? "btn-disabled opacity-0" : "btn-active opacity-100"
          }`}
          onClick={() => {
            handlePrevious();
          }}
        >
          Previous
        </button>
        <button
          className="btn text-white btn-neutral w-24"
          onClick={
            step < 3
              ? () => {
                  handleNext();
                }
              : undefined
          }
          type={step >= 3 ? "submit" : undefined}
          form={step >= 3 ? "visa-form" : undefined}
        >
          {step >= 3 ? "Submit" : "Next"}
        </button>
      </div>
    </div>
  );
}
reactjs typescript forms next.js react-hook-form
1个回答
0
投票

您可以有两个按钮,在最后一个阶段应呈现提交按钮,在步骤上应呈现下一个按钮,例如 {步骤< 3 && next

© www.soinside.com 2019 - 2024. All rights reserved.