subscribe:
UseFormSubscribe<TFieldValues extends FieldValues>
订阅 formState
的更改和值更新。你可以订阅单个字段或整个表单,同时避免表单更改导致的不必要的重新渲染。
¥Subscribe to formState
changes and value updates. You can subscribe to individual fields or the entire form, while avoiding unnecessary re-renders caused by form changes.
属性
¥Props
名称 | 类型 | 描述 | 示例 |
---|---|---|---|
name | undefined | 订阅整个表单 | subscribe() |
string[] | 通过名称订阅多个字段。 | subscribe({ name: ['firstName', 'lastName'] }) | |
formState | Partial<ReadFormState> | 选择要订阅的 formState 。 | |
callback | Function | 订阅的回调函数。 | |
exact | boolean | 此属性将为输入名称订阅启用精确匹配。 | subscribe({ name: 'target', exact: true }) |
This function is intended for subscribing to changes only; dispatching state updates or triggering re-renders is not allowed. eg
setValue
orreset
此函数与 和
createFormControl.subscribe
功能相同,主要区别在于 createFormControl 可以在 React 组件外部初始化。¥This function shares the same functionality as
createFormControl.subscribe
, with the key difference being that createFormControl can be initialized outside of a React component.此函数专用于订阅表单状态(无需渲染),请使用此函数代替 watch 回调函数。
¥This function is dedicated for subscribe form state without render, use this function for that instead of watch callback function.
示例:
¥Examples:
import { useForm } from "react-hook-form"type FormInputs = {firstName: stringlastName: string}export default function App() {const { register, subscribe } = useForm<FormInputs>()useEffect(() => {// make sure to unsubscribe;const callback = subscribe({formState: {values: true},callback: ({ values }) => {console.log(values);}})return () => callback();// You can also just return the subscribe// return subscribe();}, [subscribe])return (<form><input {...register("firstName", { required: true })} /><input {...register("lastName", { required: true })} /></form>)}