【问题标题】:forwardRef on Select does not save chosen value with react-hook-form选择上的 forwardRef 不会使用 react-hook-form 保存选择的值
【发布时间】:2021-12-05 15:52:44
【问题描述】:

我正在构建一个反应组件库。

此文本字段通过将refforwardRef 一起传递来工作:

export const TextField = React.forwardRef((props:TextFieldProps, ref) => {

return (
    <input ref={ref}....

但是,当我尝试使用 select 进行相同操作时:

export const SimpleSelect = React.forwardRef((props: SimpleSelectProps, ref: Ref<HTMLSelectElement>) => {

const options = props.options

return (
  <select ref={ref}  className="Select">
    <option>-- Select an option --</option>
    {options &&
      options.map((option: OptionsType) => (
        <option key={option.value} value={option.value}>
          {option.label}
        </option>

然后我在自己的应用程序中使用,如下所示:

<form onSubmit={handleSubmit(onSubmit)}>
  <SimpleSelect
    {...register('thingId', { required: true })}
    title="Thing"
    options={
      things &&
      things.map(({ thing }: Thing) => ({
        value: thing.uid,
        label: thing.primaryName,
      }))
    }
  />

选择的选项没有保存,我可以看到当我提交表单时,即使选择了一个选项,它也会尝试提交“--选择一个选项--”。

【问题讨论】:

    标签: react-hook-form reactjs react-hook-form react-forwardref


    【解决方案1】:

    您需要在select 组件中传播RHF 提供的props 以使您的控件正常工作。具体来说,select 需要一个 name 属性以便可以识别它,onChange 以便 RHF 可以监听选项更改事件:

    <select ref={ref} className="Select" {...props}>
    

    【讨论】:

    • 非常感谢
    • 我以前从没想过!谢谢你。对我有很大帮助
    猜你喜欢
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2021-12-11
    • 2021-12-01
    • 2022-11-10
    • 2020-07-16
    • 2021-11-21
    • 2021-05-25
    相关资源
    最近更新 更多