听起来很简单,但尽管文档内容丰富,但我找不到这方面的 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>
Run Code Online (Sandbox Code Playgroud)
处理程序将 selectedProductName、selectedProductIndex 等的值保存在 useState 中,通过 axios 等保存在数据库中。我在 useState 中单独处理每个字段的值,我知道这是费力且粗暴的。
Fra*_*cis 16
答案很简单,尽管我花了一段时间才弄清楚。在大多数示例中,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;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22785 次 |
最近记录: |