问题描述
我正在使用“ 反应挂钩形式”库构建一个简单的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>
</>
);
}