【问题标题】:react-hook-form can't correctly validation with value and onChange after submitreact-hook-form 提交后无法正确验证 value 和 onChange
【发布时间】:2021-01-27 22:44:25
【问题描述】:

我有组件:

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

【问题讨论】:

  • 我认为你正在混合受控和不受控。如果你想使用受控输入,我建议使用控制器。

标签: reactjs onchange react-hook-form


【解决方案1】:

不需要有 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>
   );
 };

【讨论】:

  • 谢谢,但我需要valueonChange。这是我的组件的简化版本。我正在使用 onChange 将值发送到父组件,value 如果用户更改父组件中的某些内容,我将使用从父组件获取数据
  • 这不是问题,我更新了示例以满足您的需求。让我知道这对你有用吗。
【解决方案2】:

调用useForm时必须使用mode:"onChange"

代码示例:

const { register, handleSubmit, formState: { errors } } = useForm({
    resolver: yupResolver(schema),
    mode: "onBlur",
    // mode:"onChange",
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 2023-03-17
    • 2022-08-12
    • 2021-05-16
    • 1970-01-01
    • 2022-08-18
    • 2021-11-01
    相关资源
    最近更新 更多