trigger:
(name?: string | string[]) => Promise<boolean>
手动触发表单或输入验证。当你具有依赖验证(输入验证取决于另一个输入的值)时,此方法也很有用。
¥Manually triggers form or input validation. This method is also useful when you have dependant validation (input validation depends on another input's value).
属性
¥Props
名称 | 类型 | 描述 | 示例 |
---|---|---|---|
name | undefined | 触发所有字段的验证。 | trigger() |
string | 按名称触发对特定字段值的验证 | trigger("yourDetails.firstName") | |
string[] | 按名称触发多个字段的验证。 | trigger(["yourDetails.lastName"]) | |
shouldFocus | boolean | 设置错误时应集中输入。这仅在注册输入引用时有效,它也不适用于自定义注册。 | trigger('name', { shouldFocus: true }) |
RULES
隔离渲染优化仅适用于以 string
作为负载的单个字段名称,当提供 array
和 undefined
来触发时,将重新渲染整个 formState。
¥Isolate render optimisation only applicable for targeting a single field name with string
as payload, when supplied with array
and undefined
to trigger will re-render the entire formState.
示例:
¥Examples:
import React from "react"import { useForm } from "react-hook-form"type FormInputs = {firstName: stringlastName: string}export default function App() {const {register,trigger,formState: { errors },} = useForm<FormInputs>()return (<form><input {...register("firstName", { required: true })} /><input {...register("lastName", { required: true })} /><buttontype="button"onClick={() => {trigger("lastName")}}>Trigger</button><buttontype="button"onClick={() => {trigger(["firstName", "lastName"])}}>Trigger Multiple</button><buttontype="button"onClick={() => {trigger()}}>Trigger All</button></form>)}
视频
¥Video
下面的视频详细解释了 trigger
API。
¥The following video explain trigger
API in detail.