使用React Hook Form中的useFormState Hook来代替useWatch Hook,可以实现监视表单中特定字段的变化。
代码示例:
import React from 'react';
import { useForm, useFormState } from 'react-hook-form';
function App() {
const { register, handleSubmit } = useForm();
const { watch } = useFormState();
const onSubmit = (data) => console.log(data);
const watchedValue = watch('fieldName');
return (
);
}
在这个例子中,我们使用useForm和useFormState钩子来注册表单中的字段和监视特定字段的变化。watch函数用于监视特定字段的值。当字段的值发生变化时,watchedValue变量将更新。在表单提交时,onSubmit函数将被调用并将表单数据作为参数传递。