reactjs - 提交后,react-hook-form 无法正确验证值和 onChange

标签 reactjs onchange react-hook-form

我有组件:

const FormComponent = () => {
  const { register, handleSubmit, errors } = useForm();

  const [val, setVal] = useState("");

  const handleSubmitForm = () => console.log("send!");

  const handleChange = (e) => {
    setVal(e.target.value);
  };

  return (
    <form onSubmit={handleSubmit(handleSubmitForm)}>
      <input
        type="text"
        name="test"
        value={val}
        ref={register({ required: "The field is required." })}
        onChange={handleChange}
      />
      {errors.test && errors.test.message}
      <button type="submit">Send</button>
    </form>
  );
};
当我点击“提交”时,react-hook-form显示错误消息:'该字段是必需的。
'。当我想写单词“TEST”然后我尝试删除此文本时,例如选择所有文本并单击 Backspace 按钮,然后我无法从输入中删除此文本,但显示有关空值的消息。
我如何使用 react-hook-formvalueonChange事件?
Demo codesandbox

最佳答案

不需要有 value 和 onChange。您可以使用不受控制的形式,如果您需要其中一个输入的值,您可以简单地观看它;-)

const FormComponent = () => {
   const { register, handleSubmit, watch, errors } = useForm(); 
   const handleSubmitForm = (data) => console.log(data);
 
   const valueOfTest = watch('test');

   useEffect(() => {
      //consider this to be onchange function
      doSomething(valueOfTest);
   }, [valueOfTest]);
 
   return (
     <form onSubmit={handleSubmit(handleSubmitForm)}>
       <input
         type="text"
         name="test"
         ref={register({ required: "The field is required." })}
       />
       {errors.test && errors.test.message}
       <button type="submit">Send</button>
     </form>
   );
 };

关于reactjs - 提交后,react-hook-form 无法正确验证值和 onChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65928525/

相关文章:

node.js - NPM:npm 安装在 fetchMetaData -> addTmpTa 上挂起

javascript - 如何在 React js 中设置响应式样式以响应模态?

javascript - 我如何以编程方式更改选择,以便它触发其 onchange 行为?

php - 使用 html 代码附加字符串

reactjs - @mui v5 自动完成与 React Hook Form 7 不起作用?

javascript - React-hook-form 验证不适用于自定义字段数组

node.js - react-hook-form & material-UI 选择

javascript - 将不相交的力定向图放入 React 应用程序

reactjs - 属性 'isLoading' 在类型 'IntrinsicAttributes & IntrinsicClassAttributes<FormInstance<{}, Partial<ConfigProps<{}, {}>> -Redux 表单中不存在

javascript - 当输入类型 ="date"的日期明确作为第一个操作时,onchange 不会触发