首页 > 解决方案 > 使用 react-hook-form,如何根据选择以编程方式修改输入的值?

问题描述

听起来很简单,但我找不到一个 hello-world 的例子,尽管文档很丰富。我能找到的最接近的是https://react-hook-form.com/advanced-usage,在使用虚拟化列表部分,但这依赖于另一个模块 react-window,它引入了进一步的复杂性。

我想允许管理员用户创建-更新-删除具有各种属性的产品列表。

我当前在 JSX 中的代码如下所示,我想利用 react-hook-form 中的错误处理等:

<ol >
  {products.map((row, index) => (
        <li 
            className={index === selectedProductIndex ? "selected" : ""} 
            key={index} 
            id={index} onClick={handleSelectProduct}>
            {row.name}
        </li>
    ))}
</ol>
<form onSubmit={handleSaveProduct}>
       <p>Product name: </p>
          <input name="productName" type="text" value={selectedProductName} 
          onChange={handleEdit_name} />
           (... more properties to edit here)
                
              </form>

处理程序将 selectedProductName、selectedProductIndex 等的值保存在 useState 中,通过 axios 等保存在数据库中。我在 useState 中单独处理每个字段的值,我知道这很费力且手忙脚乱。

标签: react-hook-form

解决方案


答案很简单,虽然我花了一段时间才弄明白。在大多数示例中,onChange 或 onClick 处理程序不使用事件对象,但没有什么可以阻止您添加它。然后是 setValue 函数来设置其他控件的值。这是一个 hello-world 示例的代码。它提供一个下拉菜单和一个输入字段,输入字段会更新以匹配下拉列表的选定值。

import React from "react";
import { useForm } from "react-hook-form";

function Test() {
const { register, handleSubmit,  errors, setValue } = useForm();
const mySubmit =  data => { console.log(data); }

return(
<div >
    <form  onSubmit={handleSubmit(mySubmit)}   className="reacthookform" >
      <select  name="dropdown" ref={register} 
           onChange={(ev)=> setValue("productName", ev.target.value )} >
         {["AAA", "BBB", "CCC"].map(value => (
         <option key={value} value={value}> 
             {value}
         </option>
         ))}
       </select>
      <input name="productName" defaultValue="AAA" ref={register({ required: true })} className="big" />
      {errors.productName && <p className="errorMessage">This field is required</p>}
      <input type="submit" value="Save product" />
  </form>
</div>
 );
}
export default Test;

推荐阅读