Skip to content

watch

订阅输入更改

</> watch: (names?: string | string[] | (data, options) => void) => unknown

此方法将监视指定的输入并返回它们的值。它对于渲染输入值和确定按条件渲染什么很有用。

¥This method will watch specified inputs and return their values. It is useful to render input value and for determining what to render by condition.

属性

¥Props


类型描述
string按名称监视输入值(类似于 lodash get 功能)
string[]观察多个输入
undefined观察所有输入
(data: unknown, { name: string, type: string }) => void监视所有输入并调用回调

返回

¥Return


示例返回
watch('inputName')unknown
watch(['inputName1'])unknown[]
watch(){[key:string]: unknown}
watch((data, { name, type }) => console.log(data, name, type)){ unsubscribe: () => void }
RULES
  • defaultValue 未定义时,watch 的第一次渲染将返回 undefined,因为它在 register 之前被调用。建议在 useForm 处提供 defaultValues 以避免这种行为,但你可以将内联 defaultValue 设置为第二个参数。

    ¥When defaultValue is not defined, the first render of watch will return undefined because it is called before register. It's recommended to provide defaultValues at useForm to avoid this behaviour, but you can set the inline defaultValue as the second argument.

  • defaultValuedefaultValues 都提供时,将返回 defaultValue

    ¥When both defaultValue and defaultValues are supplied, defaultValue will be returned.

  • 此 API 将在应用或表单的根部触发重新渲染,如果你遇到性能问题,请考虑使用回调或 useWatch api。

    ¥This API will trigger re-render at the root of your app or form, consider using a callback or the useWatch api if you are experiencing performance issues.

  • watch 结果针对渲染阶段而不是 useEffect 的 deps 进行了优化,为了检测值更新,你可能需要使用外部自定义钩子进行值比较。

    ¥watch result is optimised for render phase instead of useEffect's deps, to detect value update you may want to use an external custom hook for value comparison.

示例:

¥Examples:


在表单中监视

¥Watch in a Form

import React from "react"
import { useForm } from "react-hook-form"
interface IFormInputs {
name: string
showAge: boolean
age: number
}
function App() {
const {
register,
watch,
formState: { errors },
handleSubmit,
} = useForm<IFormInputs>()
const watchShowAge = watch("showAge", false) // you can supply default value as second argument
const watchAllFields = watch() // when pass nothing as argument, you are watching everything
const watchFields = watch(["showAge", "age"]) // you can also target specific fields by their names
// Callback version of watch. It's your responsibility to unsubscribe when done.
React.useEffect(() => {
const subscription = watch((value, { name, type }) =>
console.log(value, name, type)
)
return () => subscription.unsubscribe()
}, [watch])
const onSubmit = (data: IFormInputs) => console.log(data)
return (
<>
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("name", { required: true, maxLength: 50 })} />
<input type="checkbox" {...register("showAge")} />
{/* based on yes selection to display Age Input*/}
{watchShowAge && (
<input type="number" {...register("age", { min: 50 })} />
)}
<input type="submit" />
</form>
</>
)
}
import React from "react"
import { useForm } from "react-hook-form"
function App() {
const {
register,
watch,
formState: { errors },
handleSubmit,
} = useForm()
const watchShowAge = watch("showAge", false) // you can supply default value as second argument
const watchAllFields = watch() // when pass nothing as argument, you are watching everything
const watchFields = watch(["showAge", "number"]) // you can also target specific fields by their names
// Callback version of watch. It's your responsibility to unsubscribe when done.
React.useEffect(() => {
const subscription = watch((value, { name, type }) =>
console.log(value, name, type)
)
return () => subscription.unsubscribe()
}, [watch])
const onSubmit = (data) => console.log(data)
return (
<>
<form onSubmit={handleSubmit(onSubmit)}>
<input type="checkbox" {...register("showAge")} />
{/* based on yes selection to display Age Input*/}
{watchShowAge && (
<input type="number" {...register("age", { min: 50 })} />
)}
<input type="submit" />
</form>
</>
)
}

在字段数组中监视

¥Watch in Field Array

import * as React from "react"
import { useForm, useFieldArray } from "react-hook-form"
type FormValues = {
test: {
firstName: string
lastName: string
}[]
}
function App() {
const { register, control, handleSubmit, watch } = useForm<FormValues>()
const { fields, remove, append } = useFieldArray({
name: "test",
control,
})
const onSubmit = (data: FormValues) => console.log(data)
console.log(watch("test"))
return (
<form onSubmit={handleSubmit(onSubmit)}>
{fields.map((field, index) => {
return (
<div key={field.id}>
<input
defaultValue={field.firstName}
{...register(`test.${index}.firstName`)}
/>
<input
defaultValue={field.lastName}
{...register(`test.${index}.lastName`)}
/>
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
)
})}
<button
type="button"
onClick={() =>
append({
firstName: "bill" + renderCount,
lastName: "luo" + renderCount,
})
}
>
Append
</button>
</form>
)
}
import * as React from "react"
import { useForm, useFieldArray } from "react-hook-form"
function App() {
const { register, control, handleSubmit, watch } = useForm()
const { fields, remove, append } = useFieldArray({
name: "test",
control,
})
const onSubmit = (data) => console.log(data)
console.log(watch("test"))
return (
<form onSubmit={handleSubmit(onSubmit)}>
{fields.map((field, index) => {
return (
<div key={field.id}>
<input
defaultValue={field.firstName}
{...register(`test.${index}.firstName`)}
/>
<input
defaultValue={field.lastName}
{...register(`test.${index}.lastName`)}
/>
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
)
})}
<button
type="button"
onClick={() =>
append({
firstName: "bill" + renderCount,
lastName: "luo" + renderCount,
})
}
>
Append
</button>
</form>
)
}

视频

¥Video


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