簡體   English   中英

如何將 react-hook-form 與 react-datepicker 選擇范圍一起使用?

[英]How is it possible to use react-hook-form with react-datepicker select range?

我想用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識別選擇器中的開始或結束時間? 可能嗎?

我上周遇到了完全相同的問題,這是解決方案...

您只需將(至少)值傳遞給“控制器函數”,您只需使用字段對象即可實現。

在任何情況下,當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`,
                }}
              />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM