【问题标题】:Button Onclick is does not hit the submit Function in nextjs按钮 Onclick 未命中 nextjs 中的提交功能
【发布时间】:2022-01-18 07:01:40
【问题描述】:

我正在做一个 nextjs 项目。

我用按钮创建了一个表单。 当我点击按钮时,表单应该提交。

但在我的情况下,Onclik 是行不通的。

这是我的代码

                                    <Button
                                        variant="outlined"
                                        color="primary"
                                        id="BookinEnquireCloseBtnDesktop"
                                        type="submit"
                                        onClick={handleSubmit(onCardSubmit)}
                                    >
                                        Submit
                                    </Button>
 const {
       handleSubmit,
       register,
       formState: { isSubmitting },
   } = useForm<IPaymentForm>({
          defaultValues: {
               amount : 20,
               description : "demo"
          },
       resolver: yupResolver(paymentSchema),
       mode: 'all',
   });
    const onCardSubmit = async (value: IPaymentForm): Promise<void> => {
     console.log("hit");

        const paymentDto: PaymentDto = {
            paymentRequest: {
                amount: value.amount,
                description: value.description,            },
        };
    };

编辑:

我试过了

  <form
                                    onSubmit={handleSubmit(onCardSubmit)}
                                >
<Button

                                        variant="outlined"
                                        type="submit"
                                        disabled={isSubmitting}
                                    >
                                        {!isSubmitting ? 'Submit' : <CircularProgress />}
                                    </Button>

</form>

这也不会触发 onCardSubmit() 函数。

【问题讨论】:

  • “提交”类型的&lt;button /&gt; 将触发其关联的表单元素的onSubmit 处理程序。 Here are the docs。您应该将 handleSubmit 调用移动到 &lt;form&gt; 元素。
  • 您好,我已经按照您说的进行了尝试。但这也不起作用查看我编辑的问题
  • useFormButton 来自哪里?

标签: reactjs typescript next.js


【解决方案1】:

我认为您处理的是单击按钮,而不是处理提交事件时表单上的表单数据,如下所示:

<form onSubmit={handleSubmit(onSubmit)}>
  <input {...register("firstName")} />
  <p>{errors.firstName?.message}</p>
    
  <input {...register("age")} />
  <p>{errors.age?.message}</p>
  
  <input type="submit" />
</form>

【讨论】:

  • 嗨,请查看我编辑的问题。你说的我试过了
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-12
  • 2019-06-22
  • 2013-07-27
  • 1970-01-01
相关资源
最近更新 更多