跳到内容

handleSubmit

准备发送到服务器

</> handleSubmit: ((data: Object, e?: Event) => Promise<void>, (errors: Object, e?: Event) => Promise<void>) => Promise<void>

如果表单验证成功,此函数将接收表单数据。

Props


名称类型描述
SubmitHandler(data: Object, e?: Event) => Promise<void>成功的回调函数。
SubmitErrorHandler(errors: Object, e?: Event) => Promise<void>错误回调函数。
规则
  • 您可以使用 handleSubmit 轻松地异步提交表单。

    handleSubmit(onSubmit)()
    // You can pass an async function for asynchronous validation.
    handleSubmit(async (data) => await fetchAPI(data))
  • disabled 输入将在表单值中显示为 undefined 值。如果您想阻止用户更新输入并希望保留表单值,可以使用 readOnly 或禁用整个 <fieldset />。这里有一个 示例

  • handleSubmit 函数不会吞并 onSubmit 回调函数内部发生的错误,因此我们建议您尝试在异步请求中进行捕获,并为您的客户优雅地处理这些错误。

    const onSubmit = async () => {
    // async request which may result error
    try {
    // await fetch()
    } catch (e) {
    // handle your error
    }
    };
    <form onSubmit={handleSubmit(onSubmit)} />

示例


同步

import React from "react"
import { useForm, SubmitHandler } from "react-hook-form"
type FormValues = {
firstName: string
lastName: 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("firstName")} />
<input {...register("lastName")} />
<input type="email" {...register("email")} />
<input type="submit" />
</form>
)
}
import { useForm } from "react-hook-form"
export default function App() {
const { register, handleSubmit } = useForm()
const onSubmit = (data, e) => console.log(data, e)
const onError = (errors, e) => console.log(errors, e)
return (
<form onSubmit={handleSubmit(onSubmit, onError)}>
<input {...register("firstName")} />
<input {...register("lastName")} />
<button type="submit">Submit</button>
</form>
)
}

异步

import React from "react";
import { useForm } from "react-hook-form";
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
function App() {
const { register, handleSubmit, formState: { errors }, formState } = useForm();
const onSubmit = async data => {
await sleep(2000);
if (data.username === "bill") {
alert(JSON.stringify(data));
} else {
alert("There is an error");
}
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label htmlFor="username">User Name</label>
<input placeholder="Bill" {...register("username"} />
<input type="submit" />
</form>
);
}

视频


以下视频教程详细解释了 handleSubmit API。

感谢您的支持

如果您发现 React Hook Form 在您的项目中很有用,请考虑为它加星并支持它。