如何在本机HTML上使用React-Hook-form设置值
我的目标是在项目中使用所有本机HTML元素,并且我目前使用React表单挂钩进行了工作输入和复选框,但我似乎无法获得选择(多个)工作。
具体而言,不起作用的部分是我去更新某些数据时从服务器检索的值的值设置(以其他方式起作用)。
这是我拥有的相关代码:
注意,以下是文件中的实际代码,但是我试图删除与问题无关的所有内容。在原始代码中,还具有从后端获取数据并处理创建和删除操作的功能,以及一些与此问题无关的用户界面内容。
从后端返回的数据是JSON对象,它是我所谓的类型的数组。每种类型都有一个ID,名称和一个子类型数组,该字体还具有ID,名称和一个称为“连接”的值,该值是一个布尔值,可以确定所涉及的类型是否连接到子类型。这里的目标是拥有这些类型的表,然后在该表中单击一行时,您可以通过更改名称和/或更改选择哪些子类型(选定的类型为connected = true = true)来编辑该特定
import React, { useState, useEffect } from 'react';
import { useForm } from "react-hook-form";
import { ErrorMessage } from '@hookform/error-message';
import { RootStateOrAny, useSelector, useDispatch } from 'react-redux';
import { updateTicketTypeAction } from '../../actions/ticketActions';
interface ttFormInputs {
name: string;
sub_types: [];
}
export default function Ticket() {
const {
register,
resetField,
formState: { errors },
handleSubmit,
setValue
} = useForm<ttFormInputs>();
const types = useSelector((state: RootStateOrAny) => state.root.ticket.types);
const onToggleEdit = ((type: any) => {
setValue('name', type.name) //this does work
/* this doesn't work
Note, in both of these tests, I am not even looking at the 'connected' property
of the subtype. I'm just trying to pre-select all of them to see if it can be
done in any way.
type.sub_types.map((value: any) => {
setValue('sub_types', value.id, { shouldTouch: true })
})
*/
/* nor does this...
note: stypes in this case ends up being a simple array of ids
*/
let stypes = type.sub_types.map((value: any) => (value.id))
setValue('sub_types', stypes, { shouldTouch: true })
})
const dispatch = useDispatch()
const onUpdateTicketType = handleSubmit(async (data: ttFormInputs) => {
dispatch(updateTicketTypeAction(data))
resetField("name")
resetField("sub_types")
})
const typeList = types.map((type: any) =>
<tr key={ type.id }>
<td>
{
<>
<input {...register("name", { required: "Name is required"})} />
<ErrorMessage errors={errors} name="name" />
</>
}
</td>
<td>
{
<select {...register("sub_types")} multiple>
{
type.sub_types.map((value: any) => (
<option key={value.id} value={value.id}> // Note, I've also tried selected={value.connected} here, but this did not work either.
{value.name}
</option>
))
}
</select>
}
</td>
<td>
<input type="submit" />
</td>
<td>
<button onClick={(e) => onDeleteTicketType(e, type.id)}>Delete</button>
</td>
</tr>
);
return (
<div>
<h4 className="pageTitle">Ticket Configuration</h4>
<form onSubmit={onUpdateTicketType}>
<table>
<thead>
<tr>
<th>Ticket Type</th>
<th>Sub-Types</th>
<th>Parent-Types</th>
<th></th>
</tr>
</thead>
<tbody>
{ types && typeList }
</tbody>
</table>
</form>
</div>
);
}
类型要找到任何使用本机HTML选择标签与React-Hok-Form结合使用的方式。似乎每个示例都使用某种UI工具包,例如Bootstrap或其他其他示例,我特别尝试避免使用类似的工具。
可以做到吗?
My goal is to use all native html elements in my project and I currently have working input and checkboxes using react form hook but I can't seem to get a select (multiple) to work.
Specifically, the part that doesn't work is the setting of the values with values retrieved from the server when I go to update some data (it works in every other way).
Here is the relevant code I have:
Note, Below is the actual code from my file however I have tried to remove everything that did not seem relevant to the question. In the original code there are also functions to get the data from the backend and to handle the create and delete actions as well as some user interface stuff that again is irrelevant (i think) to this question.
The data returned from the backend is a JSON object which is an array of what I call types. Each type has an id, name and an array of subtypes which also have ids, names and a value called 'connected' which is a boolean to determine if the type in question is connected to the subtype. The goal here is to have a table of these types and upon clicking a row in that table you can edit that particular type by changing the name and/or changing which subtypes are selected (selected types are the connected=true ones)
import React, { useState, useEffect } from 'react';
import { useForm } from "react-hook-form";
import { ErrorMessage } from '@hookform/error-message';
import { RootStateOrAny, useSelector, useDispatch } from 'react-redux';
import { updateTicketTypeAction } from '../../actions/ticketActions';
interface ttFormInputs {
name: string;
sub_types: [];
}
export default function Ticket() {
const {
register,
resetField,
formState: { errors },
handleSubmit,
setValue
} = useForm<ttFormInputs>();
const types = useSelector((state: RootStateOrAny) => state.root.ticket.types);
const onToggleEdit = ((type: any) => {
setValue('name', type.name) //this does work
/* this doesn't work
Note, in both of these tests, I am not even looking at the 'connected' property
of the subtype. I'm just trying to pre-select all of them to see if it can be
done in any way.
type.sub_types.map((value: any) => {
setValue('sub_types', value.id, { shouldTouch: true })
})
*/
/* nor does this...
note: stypes in this case ends up being a simple array of ids
*/
let stypes = type.sub_types.map((value: any) => (value.id))
setValue('sub_types', stypes, { shouldTouch: true })
})
const dispatch = useDispatch()
const onUpdateTicketType = handleSubmit(async (data: ttFormInputs) => {
dispatch(updateTicketTypeAction(data))
resetField("name")
resetField("sub_types")
})
const typeList = types.map((type: any) =>
<tr key={ type.id }>
<td>
{
<>
<input {...register("name", { required: "Name is required"})} />
<ErrorMessage errors={errors} name="name" />
</>
}
</td>
<td>
{
<select {...register("sub_types")} multiple>
{
type.sub_types.map((value: any) => (
<option key={value.id} value={value.id}> // Note, I've also tried selected={value.connected} here, but this did not work either.
{value.name}
</option>
))
}
</select>
}
</td>
<td>
<input type="submit" />
</td>
<td>
<button onClick={(e) => onDeleteTicketType(e, type.id)}>Delete</button>
</td>
</tr>
);
return (
<div>
<h4 className="pageTitle">Ticket Configuration</h4>
<form onSubmit={onUpdateTicketType}>
<table>
<thead>
<tr>
<th>Ticket Type</th>
<th>Sub-Types</th>
<th>Parent-Types</th>
<th></th>
</tr>
</thead>
<tbody>
{ types && typeList }
</tbody>
</table>
</form>
</div>
);
}
I am struggling to find any way of using native html select tags in conjunction with react-hook-form. It seems that every example uses some sort of UI toolkit like bootstrap or something else and I am specifically trying to avoid tools like this.
Can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然,在为此挣扎了一天并终于在这里发布后,大约10分钟后,我找到了答案。在这里发布,这样别人就不需要经历同样的痛苦。
答案非常接近我在上面示例中已经尝试使用的Ettybes变量的答案。问题在于我正在创建一系列数字,并且选项中的键设置为字符串,因此它们从未匹配。这是我最终做到的:
and of course, after struggling with this for a day and finally posting in here, I found the answer about 10 minutes later. Posting here so someone else doesn't need to go through the same pain.
The answer was very close to what I had already tried with my stypes variable in the example above. The problem was that I was creating an array of numbers and the keys in the options were set to strings so they never matched. Here is what I ended up with that worked: