gpt4 book ai didi

reactjs - React-hook-form 即使在未触及的字段上也会将 `undefined` 更改为空字符串

转载 作者:行者123 更新时间:2023-12-05 05:46:42 25 4
gpt4 key购买 nike

我有一个表单和一些默认值,如下所示:

const defaultValues = {text: 'text'};
reset(defaultValues);

在表单中,有两个名为 texttitle 的文本输入。

问题是,每次表单状态发生变化时,title 的值都会变成空字符串:

  useEffect(() => {
const form = getValues();
console.info(form, formState.touchedFields);
}, [formState]);

给出:{text: 'text', title: ''} 和一个用于 touchedFields 的空对象。这一点非常关键,因为在应用程序中,未定义值和空字符串之间存在很大差异。

我怎样才能让 RHF 不改变未改变的值?

编辑:看看这个例子:https://codesandbox.io/s/clever-jang-d2s4n?file=/src/App.js

最佳答案

因此,按照这里的建议 https://github.com/react-hook-form/react-hook-form/discussions/7826解决方案是使用 Controller :

const {
formState: { errors },
setValue
} = useFormContext<T>();
const { field } = useController<T>({ name });
...
<YourInputComponent
value={field.value}
onChange={(e) => {
setValue(name, e.target.value, { shouldDirty: true, shouldValidate: true });
}}
...

不是一个理想的方式,但它有效

关于reactjs - React-hook-form 即使在未触及的字段上也会将 `undefined` 更改为空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71122999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com