我们如何在最新的 react-hooks-form 中的 onSubmit 方法中获取文本字段值

How can we get the text field value during onSubmit method in latest react-hooks-form

我们如何在版本 7.31.2 的最新 react-hooks-form 中的 onChange 方法中获取文本字段值。现在我在点击提交时得到空白值 button.Could 有人请告诉我这个。

这是我的 CSB link 供参考: https://codesandbox.io/s/affectionate-currying-5gng14?file=/src/App.js

const {
  register,
  handleSubmit,
  formState: { errors },
} = useForm();
const [formRegister, setRegister] = useState({ _id: "", name: "", email: "" });

const onChange = (e) => {
  e.persist();
  setRegister({ ...formRegister, [e.target.name]: e.target.value });
};

const onSubmit = (e) => {
  const formData = new FormData();

  for (let key in formRegister) {
    formData.append(key, formRegister[key]);
  }

  if (picture) formData.append("photo", picture);

  const config = {
    headers: {
      "content-type": "multipart/form-data",
    },
  };
  const fetchData = async () => {
    try {
      const res = await axios.put(
        "http://localhost:8000/service/joinrequest",
        formData,
        config
      );

      if (res.data.success) {
        setIsSent(true);
      } else {
        console.log(res.data.message);
        setHelperText(res.data.message);
      }
    } catch (e) {
      setHelperText(e.response.data.message);
    }
  };
  fetchData();
};
<form onSubmit={handleSubmit(onSubmit)} encType="multipart/form-data">
  <label>Name</label>
  <input
    id="name"
    name="name"
    type="text"
    {...register("name", {
      onChange: (e) => {
        // how can we get the value here
      },
      required: true,
      maxLength: 30,
    })}
  />
  <label>Email</label>
  <input
    id="email"
    name="email"
    type="email"
    {...register("email", {
      onChange: (e) => {
        // how can we get the value here ?
      },
      required: true,
      pattern: {
        value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
        message: "Please enter a valid email !",
      },
    })}
  />
</form>;

您可以使用 react-hook-form API 中的 watch 来获取输入字段文本的更改。您能否详细说明您的目标,为什么要这样做。这可能有助于理解我们是否可以使用 watch 以及覆盖 onChange 是否是实现它的唯一解决方案?

在注册的onChange(e)中,e是一个合成事件,其中包含一个属性 nativeEvent,其中有一个path 属性指向原生元素.

{...register("name", {
  onChange: (e) => {
    const val = e.nativeEvent.path[0].value;

    // you can update formRegister here, 
    // but note it updates on every character
    setRegister(previous => ({
      ...previous, 
      name: val
    }))


点击提交按钮

来自表单的数据被传递到 onSubmit() 回调

const onSubmit = (e) => {
    const formData = new FormData();

    console.log(e.name);  // whatever was typed into the name field

    for (let key in e) {
      formData.append(key, e[key]);
    }