跳至内容

触发器

触发整个表单的验证

trigger: (name?: string | string[]) => Promise<boolean>

手动触发表单或输入验证。此方法在您进行依赖验证(输入验证取决于另一个输入的值)时也很有用。

属性


名称类型描述示例
nameundefined触发所有字段的验证。trigger()
string通过 **name** 触发对特定字段值的验证。trigger("yourDetails.firstName")
string[]通过 **name** 触发对多个字段的验证。trigger(["yourDetails.lastName"])
shouldFocusboolean在设置错误时是否应聚焦输入。这仅在输入的引用已注册时有效,它不适用于自定义注册。trigger('name', { shouldFocus: true })
规则

仅适用于使用 `string` 作为有效负载来定位单个字段名称的隔离渲染优化,当使用 `array` 和 `undefined` 触发时,将重新渲染整个 formState。

示例


import React from "react"
import { useForm } from "react-hook-form"
type FormInputs = {
firstName: string
lastName: string
}
export default function App() {
const {
register,
trigger,
formState: { errors },
} = useForm<FormInputs>()
return (
<form>
<input {...register("firstName", { required: true })} />
<input {...register("lastName", { required: true })} />
<button
type="button"
onClick={() => {
trigger("lastName")
}}
>
Trigger
</button>
<button
type="button"
onClick={() => {
trigger(["firstName", "lastName"])
}}
>
Trigger Multiple
</button>
<button
type="button"
onClick={() => {
trigger()
}}
>
Trigger All
</button>
</form>
)
}
import React from "react"
import { useForm } from "react-hook-form"
export default function App() {
const {
register,
trigger,
formState: { errors },
} = useForm()
return (
<form>
<input {...register("firstName", { required: true })} />
<input {...register("lastName", { required: true })} />
<button
type="button"
onClick={async () => {
const result = await trigger("lastName")
// const result = await trigger("lastName", { shouldFocus: true }); allowed to focus input
}}
>
Trigger
</button>
<button
type="button"
onClick={async () => {
const result = await trigger(["firstName", "lastName"])
}}
>
Trigger Multiple
</button>
<button
type="button"
onClick={() => {
trigger()
}}
>
Trigger All
</button>
</form>
)
}

视频


以下视频详细解释了 `trigger` API。

感谢您的支持

如果您发现 React Hook Form 对您的项目有用,请考虑为其加星和支持它。