根据reactjs中的select选项值设置值时,react-hook-form未获取值

oalqel3c  于 2022-11-22  发布在  React
关注(0)|答案(4)|浏览(166)

我正在为我的项目使用react-hook-form验证。我有一个选择选项,当它更改时,我将所选选项的值设置为另一个输入,即客户,但当我提交表单时,客户值显示为空,如何解决此问题?
这是我的密码

function App() {
const [inputs, setInputs] = useState();
const [inputs1, setInputs1] = useState();

const {
register,
formState: { errors },
trigger,
handleSubmit
} = useForm({
defaultValues: {
  searchby: "searchby",
  customers: "",
  firstName: ""
  }
 });

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

const handleInputChanges = (event) => {
const name = event.target.name;
const value = event.target.value;
 setInputs(value);
 setInputs1(value);
};

  return (
<form onSubmit={handleSubmit(onSubmit)}>
  <select
    name="searchby"
    {...register("searchby", {
      required: "password is required."
    })}
    value={inputs}
    onChange={handleInputChanges}
  >
    <option selected value="searchby">
      Search By
    </option>
    <option value="customerID">Custimer ID </option>
    <option value="teleco">Teleco</option>
  </select>
  {errors.searchby && <p>This field is Required</p>}
  <label>Customer: </label>
  <input
    name="customers"
    {...register("customers")}
    value={inputs1}
    onChange={handleInputChanges}
  />

  {errors.customers && <p>This field is Required</p>}

  <label>First name: </label>
  <input {...register("firstName", { required: true })} />
  {errors.firstName && <p>This field is Required</p>}

  <input type="submit" />
  <button
    type="button"
 
      >
    Validate All
     </button>
    </form>
  );
  }

这是我提交表单时得到的结果

代码链接:codesandbox.io

gab6jxml

gab6jxml1#

您在这里混合了传统的组件处理和react-hook-form。我们将依赖react-hook-form并从那里开始。
通过查看Codesandbox,我们需要进行以下更改:

  • 首先,我们去掉所有使用的state和所有使用的onChange处理程序。
  • 让我们将useForm()调用更改为:
const {
    register,
    formState: { errors },
    setValue,
    handleSubmit
  } = useForm({
    defaultValues: {
      searchby: "searchby",
      customers: "",
      firstName: ""
    }
  });
  • 现在,我们需要提取register()提供给我们的一些函数,以便对onChange函数进行一些修改
const {onChange, ...rest} = register('searchby', {required: 'Password is required'})
  • 让我们创建一个onSelectChange处理程序,每次更改select的值时都会调用它
const handleSelectChange = (e) => {
    onChange(e);
    //change this to any value / logic you want
    setValue('customers', 'SomeValue')
  }
  • 现在,剩下的就是更新<select/>
<select
        {...rest}
        onChange={handleSelectChange}
      >
        <option selected value="searchby">
          Search By
        </option>
        <option value="customerID">Custimer ID </option>
        <option value="teleco">Teleco</option>
      </select>

完整组装示例:

function App() {
  const {
    register,
    formState: { errors },
    setValue,
    handleSubmit
  } = useForm({
    defaultValues: {
      searchby: "searchby",
      customers: "",
      firstName: ""
    }
  });

  const {onChange, ...rest} = register('searchby', {required: 'Password is required'})

  const handleSelectChange = (e) => {
    onChange(e);
    //change this to any value / logic you want
    setValue('customers', 'SomeValue')
  }

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <select
        {...rest}
        onChange={handleSelectChange}
      >
        <option selected value="searchby">
          Search By
        </option>
        <option value="customerID">Custimer ID </option>
        <option value="teleco">Teleco</option>
      </select>
      {errors.searchby && <p>This field is Required</p>}
      <label>Customer: </label>
      <input
        name="customers"
        {...register("customers")}
      />

      {errors.customers && <p>This field is Required</p>}

      <label>First name: </label>
      <input {...register("firstName", { required: true })} />
      {errors.firstName && <p>This field is Required</p>}

      <input type="submit" />
      <button type="button">Validate All</button>
    </form>
  );
}
ohfgkhjo

ohfgkhjo2#

当您使用{... register('anyFieldName')}时,它会给予您的组件react-hook-form新创建的表单字段值和处理程序,例如value & onChange处理程序等。当您使用自己的value & onChange处理程序时,它会覆盖react-hook-form的给定表单字段值& onChange处理程序。
您可以了解有关寄存器here的更多信息
这样试试

<input
  name="customers"
  {...register("customers")} 
/>
  • 我建议使用useController挂钩,因为它比register更灵活。使用register,您的组件就不受您自己的控制。*
r6vfmomb

r6vfmomb3#

这里的问题是,当选择“searchBy”选择值时,您正在动态设置“customers”输入值。在这种情况下,“customers”的onChange事件将不会被触发。但将在键入值时触发。
其中一个解决方案是在onsubmit触发器时添加动态变化的“customers”值,而不需要react-use-form的帮助

ttcibm8c

ttcibm8c4#

register方法提供refvalueonChangeonBlur作为输入,但您可以使用第二个参数传递自定义onChange,并使用setValue更新customers输入:

const {
    register,
    formState: { errors },
    trigger,
    handleSubmit,
    setValue
  } = useForm({
    defaultValues: {
      searchby: "searchby",
      customers: "",
      firstName: ""
    }
  });

...

const handleInputChanges = (event) => {
  const value = event.target.value;
  setValue("customers", value);
};

...

<select
  name="searchby"
  {...register("searchby", {
    onChange: handleInputChanges,
    required: "password is required."
  })}
>
  <option selected value="searchby">
    Search By
  </option>
  <option value="customerID">Custimer ID </option>
  <option value="teleco">Teleco</option>
</select>

相关问题