如何使用React'useForm'钩子注册'react-bootstrap-typeahead'组件?

问题描述

我正在使用“ 反应挂钩形式”库构建一个简单的html表单:https://react-hook-form.com/

我已将“ react-bootstrap-typeahead ”合并到html表单中,但无法使用'useForm'钩子注册该组件。因此,在 onSubmit 期间将忽略“ react-bootstrap-typeahead”输入数据。

“ react-bootstrap-typeahead”没有提供“名称属性,这使得难以注册组件。

我已经阅读了有关注册此类组件的不同选项的'useForm'文档,但仍然不知道如何实现:https://react-hook-form.com/get-started#Registerfields

有人有没有遇到过这样的挑战?

很高兴看到一个工作示例,以更好地了解如何在我的应用程序中实现“ react-bootstrap-typeahead” +“ react-hook-form”。谢谢!

这是我的示例代码

import useForm from 'react-hook-form';
import { Typeahead } from 'react-bootstrap-typeahead';
import 'react-bootstrap-typeahead/css/Typeahead.css';

const myForm = (props) => {

    const { register,handleSubmit,errors } = useForm();

    const onSubmit = data => {
          // api post request with form data
        })
    };

    const mydata = [ "one","two","three" ];

   return (
   <>
   <form onSubmit={handleSubmit(onSubmit)} >
   <div className="form-group">

   {/* Here I'm registering text input using ref: */}

   <input type="text" className="form-control" name="name" ref={register({ required: true })} />
                                        
   </div>
                                                             
   <div className="form-group mb-0">

   {/* How can I register the below component with useForm? */}
   <Typeahead
      id="multiple-typeahead"
      clearButton
      multiple
      options={mydata}
   />
   </div>
   <button type="submit">Save</button>
   </form>
   </>
  );
}

解决方法

这是我注册组件的方式:

import useForm from 'react-hook-form';
import { useForm,Controller } from "react-hook-form";
import 'react-bootstrap-typeahead/css/Typeahead.css';

const myForm = (props) => {

    const { register,handleSubmit,errors,control } = useForm();

    const onSubmit = data => {
          // api post request with form data
        })
    };

    const mydata = [ "one","two","three" ];

   return (
   <>
   <form onSubmit={handleSubmit(onSubmit)} >
   <div className="form-group">
   <input type="text" className="form-control" name="name" ref={register({ required: true })} />
   </div>
                                                             
   <div className="form-group mb-0">
<Controller
   as={Typeahead}
             control={control}
             name="typeahead_component"
             rules={{ required: true }}
             id="multiple-typeahead"
             clearButton
             multiple
             options={mydata}
             defaultValue=""
/>
   </div>
   <button type="submit">Save</button>
   </form>
   </>
  );
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...