我想用react-datepicker选择一个时间范围,
并且还使用 react-hook-form 在没有 input
的情况下验证 onBlur
,
这是我的代码:
<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 识别选择器中的开始或结束时间? 这可能吗?
最佳答案
我上周遇到了完全相同的问题,这是解决方案...
您只需将值传递(至少)到“ Controller 函数”,只需使用字段对象即可实现这一点。
无论如何,当DatePicker组件用于日期范围时,它将需要一个两位向量数据类型,其中开始日期和结束日期存储为字符串。但是,如果您尝试通过来自 reack-hook-form 的 onChange 函数 来操纵和控制这个组件,它就会搞砸整个事情,因为它是为一对一的数据流而设计的。然后,这些过程是单独完成的,但矢量仍然发送到 Controller 。这是代码!
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`,
}}
/>
关于javascript - 如何将react-hook-form与react-datepicker选择范围一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71507724/