为什么当我到达某个页面时我的表单会自动提交?

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

我创建了一个多步骤表单并使用

react-hook-form
zod
shadcn
。我所做的是创建一个下一个按钮,每个完成的步骤都会增加
1
。但是当我的
currentFormPage
到达
4
时,
processForm
会自动被呼叫。

我所做的是创建一个条件按钮,该按钮将根据

currentFormPage

进行渲染

日历.tsx

const [currentFormPage, setCurrentFormPage] = useState(0);

const goToNextPage = async () => {
  setCurrentFormPage((step) => step + 1);
};

const processForm = (data) => {
    console.log(data);
  }

const form = useForm<Inputs>({
    resolver: zodResolver(formSchemaData),
    defaultValues: {
      title: "",
      email: "",
      fullName: "",
      department: "",
      dateOfEvent: "",
      purpose: "",
      startingTime: "",
      endingTime: "",
      doesHaveDryRun: "no",
      dryRunDate: "",
      dryRunStart: "",
      dryRunEnd: "",
      doesHaveTCETAssitance: ["tcet"],
      tcetOtherAssitance: "",
      meetingType: "meeting",
      meetingTypeServices: [],
      meetingTypeServiceLink: "",
    },
  });

return (
 <Form {...form}>
              <form
                onSubmit={form.handleSubmit(processForm)}
                className="space-y-8"
              >


 {currentFormPage === 1 && (
     <>
      //...set 1 one of question
     </>
  )}

{currentFormPage === 2 && (
     <>
      //...set 2 one of question
     </>
  )}

{currentFormPage === 3 && (
     <>
      //...set 3 one of question
     </>
  )}

{currentFormPage === 4 && (
     <>
      //...set 4 one of question
     </>
  )}


 {currentFormPage === 4 ? (
        <Button type="submit">Submit</Button>
      ) : (
        <Button type="button" onClick={goToNextPage}>
           Next
         </Button>
       )}
      </form>
</Form>
)
javascript reactjs react-hook-form
1个回答
0
投票

这可以通过在 processForm() 函数中调用 e.preventDefault() 来解决,这样当计数达到 4 时按钮首次呈现在屏幕上时,表单就不会自动提交。

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