reactjs 选择日期时触发onBlur

dfty9e19  于 2022-11-04  发布在  React
关注(0)|答案(1)|浏览(148)

我正在使用带有标志open的受控日期选择器,该标志可用于打开或关闭日期选择器。当在外部单击时,onBlur被触发,导致其关闭。但当我试图选择范围时,它不允许我,而是关闭。

import React, { useState } from "react";
import "./styles.scss";
import { DatePicker } from "antd";
import "antd/dist/antd.css";

const { RangePicker } = DatePicker;

export default function Working() {
  const [pickerValue, setPickerValue] = useState(null);
  const [open, setOpen] = useState(false);

  return (
    <RangePicker
      open={open}
      onOpenChange={() => setOpen(true)}
      className="custom-datepicker"
      dropdownClassName="custom-datepicker-dropdown"
      separator={<>-</>}
      format="DD.MM.YYYY HH:mm:ss"
      onBlur={() => setOpen(false)}
      onChange={(date) => setPickerValue([date[0], date[1]])}
      value={pickerValue}
    />
  );
}

沙盒:https://codesandbox.io/s/ant-rangepicker-6gmz85?file=/src/Working.tsx:0-585

qacovj5a

qacovj5a1#

您可以添加一个处理函数以避免不需要的onBlur操作。

const handleOnBlur = () => {
  if(condition is met) {
    setOpen(false)
  }
}

...
<RangePicker
      open={open}
      onOpenChange={() => setOpen(true)}
      className="custom-datepicker"
      dropdownClassName="custom-datepicker-dropdown"
      separator={<>-</>}
      format="DD.MM.YYYY HH:mm:ss"
      onBlur={handleOnBlur}
    />

相关问题