我有这段代码,我正在尝试使用react-hook-form从Headless UI连接Combobox组件。每当我尝试输入不同的值并选择不同的选项时,都会出现错误消息 -
无法读取未定义的属性(读取“名称”)
我尝试了很多不同的变体,但无法将 Combobox 与 register 一起使用。任何帮助,将不胜感激。我想使用 register 来完成这项工作,并且不想使用其他 Controller 方法来执行 react-hook-form 的方法。
import React from "react";
import { useState } from "react";
import { Combobox } from "@headlessui/react";
import { useForm } from "react-hook-form";
const people = [
{ id: 1, name: "Durward Reynolds" },
{ id: 2, name: "Kenton Towne" },
{ id: 3, name: "Therese Wunsch" },
{ id: 4, name: "Benedict Kessler" },
{ id: 5, name: "Katelyn Rohan" },
];
function Example() {
const [query, setQuery] = useState("");
const filteredPeople =
query === ""
? people
: people.filter((person) => {
return person.name.toLowerCase().includes(query.toLowerCase());
});
const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm();
const submit = (data) => {
console.log(JSON.stringify(data));
};
return (
<form onSubmit={handleSubmit(submit)}>
<Combobox
as="div"
name="assignee"
defaultValue={people[0]}
{...register("assignee")}
>
<Combobox.Input
onChange={(event) => setQuery(event.target.value)}
displayValue={(person) => person.name}
/>
<Combobox.Options>
{filteredPeople.map((person) => (
<Combobox.Option key={person.id} value={person}>
{person.name}
</Combobox.Option>
))}
</Combobox.Options>
</Combobox>
<button>Submit</button>
</form>
);
}
export default function check() {
return (
<div>
<Example />
</div>
);
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
直接将
react-hook-form处理程序附加到Combobox可能不是一个好主意。Input > onChange将为您提供一个带有字符串target.value的事件,而不是来自的Location / User / ...模型API。您会在handleSubmit中发出复制请求来“解压”它吗?而且,如果是这样,您将如何处理 API 错误那里?!输入可能与
Combobox级别的API错误相关。您必须格外小心地在表单组件级别区分“成功”和“失败”字符串。字符串在表单组件级别可能无法解析。特别是在“多个”模式下,您可以在输入中呈现聚合信息,例如“选择了 3 个项目”。如果您将
register扩展到Combobox.Input,这将是您的值。最后,在其他一些(非 HeadlessUI)
Combobox实现中,该值将保留原始用户输入。例如:
Combobox采用新值,但Combobox.Input值仍保留“United”您可能希望坚持采用便携且面向未来的方法。
结论是相同的:让
Combobox为您解析和转换值。将onChange提供给Combobox,而不是Combobox.Input。但这只有通过受控 RHF API 变体才能实现。