【问题标题】:react date picker multi range with react hook form用反应钩子形式反应日期选择器多范围
【发布时间】:2022-06-11 23:47:52
【问题描述】:

我们使用反应钩子形式的原因是它减少了我们的状态计数并提高了性能。但是当使用日期范围作为一个日期选择器时,我不知道该怎么做。 如何在一个控制器中保存两个数据?

`() => {
  const [startDate, setStartDate] = useState(new Date());
  const [endDate, setEndDate] = useState(null);
  const onChange = (dates) => {
    const [start, end] = dates;
    setStartDate(start);
    setEndDate(end);
  };
  return (
    <DatePicker
      selected={startDate}
      onChange={onChange}
      startDate={startDate}
      endDate={endDate}
      selectsRange
      inline
    />
  );
};`

如果这段代码是我的代码,我只能捕获一个选中的值,但我需要返回2个值。如何在 react hook 表单中以最佳方式使用它?

 <Controller
            name="orderDate"
            control={control}
            render={({ field }) => (
              <DatePicker
                selected={field.value}
                onChange={(date) => field.onChange(date)}
                selectsRange
              />
            )}
          />

【问题讨论】:

    标签: reactjs react-hook-form react-datepicker


    【解决方案1】:

    上周我遇到了完全相同的问题,这是解决方案...

    您只需将值传递(至少)“Controller function”,您只需使用字段对象即可实现。

    在任何情况下,当 DatePicker 组件 用于日期范围时,它需要一个两位矢量数据类型,其中开始日期和结束日期存储为字符串。但是,如果您尝试通过来自 reack-hook-form 的 onChange 函数来操作和控制这个组件,它将会搞砸整个事情,因为它是为一对一的数据流而设计的.然后这些过程分别完成,但向量仍被发送到控制器。这是代码!

                  <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`,
                    }}
                  />
    

    【讨论】:

      猜你喜欢
      • 2021-07-16
      • 2020-10-12
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多