react-hook-form:在 select 元素中使用 readyOnly

react-hook-form: using readyOnly in a select element

我正在尝试在 select 元素中使用 readOnly,因此用户无法更改输入字段的值,但是在提交表单时我仍然需要 Api 的值和我听说在 react-hook-form 中做到这一点的唯一方法是使用 readOnly 而不是禁用,它在普通输入字段中工作但打字稿在 select 元素中给出错误。 这是代码:

interface dataProps {
  field_id: any;
  disabled: boolean;
}
<select
  readOnly={props.disabled}
  id={props.field_id}
  {...register(...)}
  defaultValue={...}
  onChange={...}
  >
  <option>
    {...}
  </option>
  renderList(...)
</select>

我试图尽可能地缩短代码,这是我得到的全部错误:

Type '{ children: any[]; defaultValue: any; onChange: (e: ChangeEvent<HTMLSelectElement>) => void; onBlur: ChangeHandler; ref: RefCallBack; name: string; readOnly: true; id: any; }' is not assignable to type 'DetailedHTMLProps<SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectElement>'.
  Property 'readOnly' does not exist on type 'DetailedHTMLProps<SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectElement>'.

我阅读了 react-hook-form 的文档,但我没有看到任何有关使用 readOnly 的信息,我登陆 this link 并且当我尝试更改在那里输入 readOnly 到 select 它给出了同样的错误,有没有办法让 readOnly 工作或者有一个解决方法来禁用将数据保存在 handleSubmit?

disabled 属性在提交时不会删除 react-hook-form 中的字段。如果您不允许用户编辑该值,您可以使用它:

// category field is still registered even when set disabled.
<select {...register("category")} disabled>

如果您真的想从提交的值中删除该字段,请在调用 register 时设置 disabled 使用 RHF 自己 API:

<input {...register("firstName", { disabled: true })}