[英]React hook Form know when value is modified
How can we know form is modified or not in react-hook-form.我们如何知道表单是否在 react-hook-form 中被修改。 Anyone have idea.任何人都有想法。 I want know if any of the value is changed and update the state edited to true.我想知道是否更改了任何值并将 state 编辑为 true。
After i provide the defaultValue to useForm({defaultValues:values}).在我将 defaultValue 提供给 useForm({defaultValues:values}) 之后。 I want to notified when the values is updated or changed from defaultValue.我想在值从 defaultValue 更新或更改时得到通知。
Use isDirty
property使用isDirty
属性
function YourComponent() {
const { formState } = useForm();
const isFormEdited = formState.isDirty;
....
Here is the docs reference这是文档参考
You can use dirtyFields from formstate also, check the length of the fields modified.您也可以使用formstate中的dirtyFields,检查修改字段的长度。
const [isEdited, setIsEdited] = useState(false);
const fieldsEdited = formState.dirtyFields;
useEffect(() => {
if (Object.keys(fieldsEdited).length > 0) {
setIsEdited(true);
} else {
setIsEdited(false);
}
}, [fieldsEdited]);
Figured out how to accomplished this.想出了如何做到这一点。 It is important to specify the defaultValues property.指定 defaultValues 属性很重要。
See the isDirty section of formState documentation :请参阅 formState文档的 isDirty 部分:
Make sure to provide all inputs' defaultValues at the useForm, so hook form can have a single source of truth to compare whether the form is dirty.确保在 useForm 中提供所有输入的 defaultValues,这样钩子表单可以有一个单一的事实来源来比较表单是否脏。
And a short example:还有一个简短的例子:
const {
formState: {
isDirty,
},
} = useForm<ProfileFormInterface>({
defaultValues: {name: 'John Doe', email: 'jd@johndoe.com'},
})
isDirty
will now only be true if the name or email changes. isDirty
现在仅在名称或 email 更改时才为真。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.