React Hook 表单控制器问题

Sum*_*mmy 3 javascript reactjs react-hooks react-hook-form

我一直在使用带有本机元素的 react 钩子表单库,但想切换到使用控制器 API 的自定义组件。

我的自定义输入组件更新 React 状态但未更新表单状态内的 ref 时遇到问题。因此,必填字段始终标记为无效,我无法提交表单。

这是我的问题的演示:https : //codesandbox.io/s/react-hook-form-controller-bofv5

它应该在提交时注销表单数据 - 但提交永远不会发生,因为表单无效。

Eli*_*ias 6

I think I have narrowed down your issue. First I removed the rules={{ required: true }} from the controller and tried the form. It told me firstName: undefined. Then I commented out the onChange attribute. After that, the form is working fine. It seems that onChange should be used if you want to provide a custom value extractor. The value needs to be returned from the function. An example of a simple input would be this: onChange={([{target}]) => target.value} reference. Additionally, it is important to note that handleSubmit extracts some internal state with the values, like that you don't need to keep track of those yourself.

This updated component seems to be working:

function App() {
  const { control, handleSubmit, errors } = useForm();
  // const [data, setData] = useState({ firstName: "" });

  const onSubmit = data => console.log(data);

  // const onChangeHandler = e => {
  //   const { name, value } = e.target;
  //   const _data = { ...data };
  //   _data[name] = value;
  //   setData(_data);
  // };

  return (
    <>
      {/* <p>{JSON.stringify(data)}</p> */}
      <form onSubmit={handleSubmit(onSubmit)}>
        <Controller
          as={Input}
          name="firstName"
          id="firstName"
          label="First Name"
          control={control}
          // value={data.firstName}
          rules={{ required: true }}
          errors={errors.firstName}
          // onChange={([e]) => onChangeHandler(e)}
        />

        <input type="submit" />
      </form>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

Just a side note, I've never worked with this library so only trust me as far as you can toss me.