gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:23:54 24 4
gpt4 key购买 nike

听起来很简单,但我找不到这样的 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 中单独处理每个字段的值,我知道这很费力而且很笨拙。

最佳答案

嗯,答案很简单,虽然我花了一段时间才弄明白。
在大多数示例中, 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;

关于react-hook-form - 使用 react-hook-form,如何根据选择以编程方式修改输入的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64596080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com