停止以 react-hook-form 形式提交表单中的输入字段

Stop an input field in a form from being submitted in react-hook-form in react

我在 react 中使用 react-hook-form npm 包进行表单验证。它有名字、姓氏、电子邮件、密码和确认密码等字段。当我点击提交时,它将由 handleSubmituseForm() 钩子处理。但是我不想在提交表单后得到的数据中包含确认密码字段值。

这里分享一下我写的代码...

<Grid item xs={12}>
 <TextField
   required
   fullWidth
   name="password"
   label="Password"
   type="password"
   id="password"
   autoComplete="new-password"
   {...register("password", { required: "Required"})}
   error={!!errors.password}
   helperText={errors?.password ? errors.password.message : null}
/>
</Grid>
<Grid item xs={12}>
  <TextField
    required
    fullWidth
    name="confirmPassword"
    label="Confirm Password"
    type="password"
    id="confirmPassword"
    {...register("confirmPassword", { 
      required: "Required",
      validate: (val) => {
      if(watch('password') != val) {
         return "Password does not match"
      }
    }
    })}
    error={!!errors.confirmPassword}
    helperText={errors?.confirmPassword ? errors.confirmPassword.message : null}
 />
 </Grid>

您可以在 handleSubmit 回调中删除这些字段:

const onSubmit = (data) => {
        delete data.confirmPassword;
        alert(JSON.stringify(data));
      };

工作示例: https://codesandbox.io/s/react-hook-form-handlesubmit-v7-uqmiy?file=/src/index.jsx:195-230 使用取消注册的另一个选项:

<div>
          <label htmlFor="password">Password</label>
          <input type="password" {...unregister("password")} placeholder="" />
</div>