跳至内容

手表

订阅输入更改

</> watch: 一些重载

此方法将监视指定的输入并返回它们的值。它对于渲染输入值和根据条件确定要渲染的内容非常有用。

重载

此函数主要服务于两种目的

  1. 返回并与字段值保持同步 a. watch(name: string, defaultValue?): unknown b. watch(names: string[], defaultValue?): {[key:string]: unknown} c. watch(): {[key:string]: unknown}
  2. 使用给定的回调函数开始订阅(可以通过调用unsubscribe函数停止) a. watch(callback: (data, { name, type }) => void, defaultValues?): { unsubscribe: () => void }

下面是这四种重载的解释。

1-a. 监视单个字段 watch(name: string, defaultValue?: unknown): unknown


监视并订阅在渲染之外使用的单个字段。

参数

名称类型描述
namestring字段名称
defaultValueunknown可选. 字段的默认值

返回单个字段值。

const name = watch("name")

1-b. 监视一些字段 watch(names: string[], defaultValue?: {[key:string]: unknown}): unknown[]


监视并订阅在渲染之外使用的字段数组。

参数

名称类型描述
namesstring[]字段名称
defaultValue{[key:string]: unknown}可选. 字段的默认值

返回一个字段值数组。

const [name, name1] = watch(["name", "name1"])

1-c. 监视整个表单 watch(): {[key:string]: unknown}


监视并订阅整个表单更新/更改,基于onChange并重新渲染在useForm上。

参数

返回整个表单值。

const formValues = watch()

2. 使用回调函数开始监视 watch(callback: (data, { name, type }) => void, defaultValues?: {[key:string]: unknown}): { unsubscribe: () => void }


订阅字段更新/更改,不触发重新渲染。

参数

名称类型描述
callback(data, { name, type }) => void回调函数,用于订阅所有字段的更改
defaultValues{[key:string]: unknown}可选. 整个表单的默认值

返回包含unsubscribe函数的对象。

useEffect(() => {
const { unsubscribe } = watch((value) => {
console.log(value)
})
return () => unsubscribe()
}, [watch])

规则


  • 当未定义defaultValue时,watch的第一次渲染将返回undefined,因为它是register之前调用的。建议useForm中提供defaultValues以避免此行为,但您可以将内联defaultValue作为第二个参数设置。
  • 当同时提供defaultValuedefaultValues时,将返回defaultValue
  • 此 API 将在您的应用程序或表单的根部触发重新渲染,如果您遇到性能问题,请考虑使用回调或useWatch API。
  • watch结果针对渲染阶段进行了优化,而不是useEffect的依赖项,为了检测值更新,您可能希望使用一个外部自定义钩子来进行值比较。

示例


在表单中监视

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>
</>
)
}

在字段数组中监视

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>
)
}

视频


感谢您的支持

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