【问题标题】:How is it possible to use react-hook-form with react-datepicker select range?如何将 react-hook-form 与 react-datepicker 选择范围一起使用?
【发布时间】:2022-06-12 00:37:42
【问题描述】:
我想用 react-datepicker 选择一个时间范围,
并且还使用 react-hook-form 来验证 onBlur 没有 input 时,
这是我的代码:
<Controller
control={control}
name='time'
rules={{ required: true }}
render={({
field: { value, onChange, onBlur }
}) => (
<Datepicker
dateFormat='yyyy/MM/dd h:mm aa'
onChange={onChange}
onBlur={onBlur}
selected={value}
showTimeSelect
/>
)}
/>
我可以在一个选择器中选择一个日期和时间并立即进行验证,
它有效,但是如果我想在一个选择器中选择两个日期和时间,我该怎么办?
如何让 react-hook-form 识别选取器中的开始时间或结束时间?
有可能吗?
【问题讨论】:
标签:
javascript
reactjs
react-hook-form
react-datepicker
【解决方案1】:
上周我遇到了完全相同的问题,这是解决方案...
您只需将值传递(至少)“Controller function”,您只需使用字段对象即可实现。
在任何情况下,当 DatePicker 组件 用于日期范围时,它需要一个两位矢量数据类型,其中开始日期和结束日期存储为字符串。但是,如果您尝试通过来自 reack-hook-form 的 onChange 函数来操作和控制这个组件,它将会搞砸整个事情,因为它是为一对一的数据流而设计的.然后这些过程分别完成,但向量仍被发送到控制器。这是代码!
const [dateRange, setDateRange] = useState([null, null]);
const [startDate, endDate] = dateRange;
<Controller
//is a prop that we get back from the useForm Hook and pass into the input.
control={control}
//is how React Hook Form tracks the value of an input internally.
name={name}
//render is the most important prop; we pass a render function here.
render={({
//The function has three keys: field , fieldState, and formState.
field, // The field object exports two things (among others): value and onChange
}) => (
<>
<DatePicker
selectsRange={true}
startDate={startDate}
endDate={endDate}
onChange={(e) => {
setDateRange(e);
field.onChange(e);
}}
isClearable={true}
className="form-control"
/>
</>
)}
rules={{
required: `The ${label} field is required`,
}}
/>