【问题标题】:react-hook-form not getting value, when value set based on select option value in reactjs当根据 reactjs 中的选择选项值设置值时,react-hook-form 没有获得值
【发布时间】:2022-11-22 17:22:12
【问题描述】:

我正在为我的项目使用 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

【问题讨论】:

标签: reactjs react-hook-form


【解决方案1】:

当您使用 {...register('anyFieldName')} 时,它会给您的组件 react-hook-form 新创建的表单字段值和处理程序,例如 value 和 onChange 处理程序,等等。当您使用自己的值和 onChange 处理程序时,它会覆盖 react-hook-form 给定的表单字段值和 onChange 处理程序。

了解更多可以注册here

像这样尝试

 <input
  name="customers"
  {...register("customers")} 
/>

我建议使用useController 钩子,因为它比register 更灵活。 使用register,您的组件不受您自己的控制。

【讨论】:

    【解决方案2】:

    这里的问题是您在选择“searchBy”选择值时动态设置“客户”输入值。在这种情况下,不会触发“客户”的 onChange 事件。但会在键入值时触发。

    解决方案之一是在没有 react-use-form 帮助的情况下在 onsubmit 触发器时添加动态更改的“客户”值

    【讨论】:

      【解决方案3】:

      您在这里混合了经典组件处理和 react-hook-form。 我们将依赖react-hook-form 并从那里开始。

      通过查看 Codesandbox,我们需要进行以下更改:

      • 首先,让我们去掉所有使用的状态和所有使用的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 处理程序,每次选择的值更改时都会调用它
        const handleSelectChange = (e) => {
          onChange(e);
          //change this to any value / logic you want
          setValue('customers', 'SomeValue')
        }
      
      • 现在,剩下的就是更新&lt;select/&gt;
            <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>
        );
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 2014-11-04
        • 1970-01-01
        • 2015-05-30
        相关资源
        最近更新 更多