如何将react-hook-forms中的寄存器与Headless UI Combobox一起使用

Nil*_*aha 6 reactjs react-hook-form headless-ui

我有这段代码,我正在尝试使用 React-hook-form 连接Headless UI中的Combobox 组件。每当我尝试输入不同的值并选择不同的选项时,都会出现错误消息 - Cannot read properties of undefined (reading 'name')

我尝试了很多不同的变体,但未能使用Comboboxwith 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>
  );
}
Run Code Online (Sandbox Code Playgroud)

小智 -2

const { register } = useFormContext();

<Combobox.Input
    {...register(id)}
    id={id}
    onChange={(event) => setQuery(event.target.value)}
/>
Run Code Online (Sandbox Code Playgroud)