javascript React数据采集器|单击图标时打开日历,但单击任意位置时关闭日历

z31licg0  于 2023-05-21  发布在  Java
关注(0)|答案(2)|浏览(163)

目前,我试图在单击图标时能够打开日历(我可以这样做),但我想在单击窗口的其他任何位置时关闭日历。
我不完全确定如何做到这一点,并希望有一些帮助
这是我的元件

const DatePicker: FC<Props> = ({
  label,
  icon,
  date,
  onChange,
  minDate,
  maxDate,
  tabIndex,
}) => {
  const dateObj = useMemo(() => (date ? date.toDate() : null), [date])
  const minDateObj = useMemo(() => (minDate ? minDate.toDate() : null), [
    minDate,
  ])
  const maxDateObj = useMemo(() => (maxDate ? maxDate.toDate() : null), [
    maxDate,
  ])

  const [calendarIsOpen, setCalendarIsOpen] = useState(false)

  return (
    <div className={css.host}>
      <div className={css.label}>{label}</div>
      <div className={css.wrapper}>
        <label>
          <button
            className={css.calendarButton}
            onClick={() => setCalendarIsOpen(!calendarIsOpen)}
          >
            {icon}
          </button>
        </label>
        <ReactDatePicker
          selected={dateObj}
          className={css.input}
          calendarClassName={css.calendar}
          showTimeSelect
          dateFormat="dd/MM/yyyy h:mm:ss aa"
          onChange={(newDate: Date) => {
            if (newDate) {
              const momentDate = moment(newDate)
              onChange(momentDate)
            }
          }}
          startDate={minDateObj}
          endDate={maxDateObj}
          minDate={minDateObj}
          maxDate={maxDateObj}
          showPopperArrow={false}
          popperModifiers={{
            offset: {
              enabled: true,
              offset: '-28px, 4px',
            },
          }}
          renderCustomHeader={customHeader}
          open={calendarIsOpen}
          tabIndex={tabIndex}
        />
      </div>
    </div>
  )
}

export default DatePicker
btqmn9zl

btqmn9zl1#

解决方案:

这个应该能用

/**
 * Hook that alerts clicks outside of the passed ref
 */
function useOutsideAlerter(ref, onOutSideClick) {
  /**
   * Alert if clicked on outside of element
   */
  function handleClickOutside(event) {
    if (ref.current && !ref.current.contains(event.target)) {
      onOutSideClick();
    }
  }

  useEffect(() => {
    // Bind the event listener
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener("mousedown", handleClickOutside);
    };
  });
}

export default function DatePicker({ onOutSideClick,...props }) {
  const wrapperRef = useRef(null);
  useOutsideAlerter(wrapperRef, onOutSideClick);
   /// your code
  return (
   // your code
  );
}

并将其命名为<DatePicker onOutsideClick={()=>{// hide this date picker component.}}/>

okxuctiv

okxuctiv2#

使用参考

const calendarRef = useRef()

然后在点击日历使用时,

calendarRef.current.calendar.disableOnClickOutside()

这个应该能用

相关问题