react-hook-form HTML select 未提交 selected 值

react-hook-form HTML select not submitting selected value

描述

我有一个简单的表单,只有一个 HTML select 和一个提交按钮。

select控件只有3个选项:

我需要访问 onchange 事件以在值出现时执行一些额外的处理 更改和提交表单之前。为简短起见,在此示例中,它只是一个 console.log 调用。

但是,无论我选择哪个选项,当我点击“发送”按钮时,它总是发送 -1 值。

重现步骤

  1. 选择任何值,在控制台上您可以看到 selected 值(5、10 等)
  2. 按提交按钮。检查控制台。

代码

import {useForm} from 'react-hook-form';

export default function HTMLSelectTest() {
const {register, handleSubmit } = useForm();
const regSel= register("sel");
const options = [
    {name: "Initial value", code: -1},
    {name: "A", code: 5},
    {name: "B", code:10}
]
    
const onSubmit = (data) => {
    console.log("data to be sent");
    console.log(data);    
};    

return (
    <form onSubmit={ handleSubmit(onSubmit) }>
        <select ref={regSel.ref}
        onChange={(e) => {
            regSel.onChange(e);            
            console.log(e.target.value); // let's say this is the additional processing 
        }}
        onBlur={(e) => {
            regSel.onBlur(e);
        }} 
        >
            {
                options.map((o, index) => {
                    return (
                        <option value={o.code} key={o.code}>
                            {o.name}
                        </option>
                    );
                })             
            }
        </select>

        <button>
            Submit
        </button>
    </form>
);
}

你很接近,你只是缺少 name 字段以允许 RHF 将更新的值绑定到相应的字段。

<select
  ref={selRef.ref}
  name={selRef.name} // add name
  onChange={(e) => {
    selRef.onChange(e);
    console.log(e.target.value);
  }}
>
...
</select>

这里是演示的codesandbox:


如果您还想保留 onBlur 并且不想手动添加 onBlur={selRef.onBlur},您可以使用解构和扩展运算符来实现。

const { onChange: selOnChange, ...selRef } = register("sel");

这里是演示的codesandbox: