Skip to content

trigger

跨表单触发验证

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


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

隔离渲染优化仅适用于以 string 作为负载的单个字段名称,当提供 arrayundefined 来触发时,将重新渲染整个 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: 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>
)
}

视频

¥Video


下面的视频详细解释了 trigger API。

¥The following video explain trigger API in detail.

React Hook Form 中文网 - 粤ICP备13048890号