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

时间:2020-10-29 17:14:44

标签: react-hook-form

听起来很简单,但是尽管文档丰富,但我找不到这个例子的例子。我能找到的最接近的是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>

处理程序通过axios等在数据库中的useState中保存selectedProductName,selectedProductIndex等的值。 我在useState中分别处理每个字段的值,我知道这很费力且费力。

1 个答案:

答案 0 :(得分:0)

答案很简单,尽管花了我一段时间才弄清楚。 在大多数示例中,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;