首页 > 解决方案 > 如何添加关闭按钮以关闭反应日期的日历?

问题描述

我正在使用 Airbnb 提供的 react-dates。它适用于桌面和移动视图。

唯一的事情是当我在移动视图上渲染日历时。有什么办法可以为日历创建一个关闭按钮?

这是它在我的移动视图上的外观:

在此处输入图像描述

我想要的是右上角的关闭 [X] 按钮来关闭日历。现在我需要在关闭之前选择日期。

我的代码DatePickerRange

import React, { useState } from 'react';
import 'react-dates/initialize';
import 'react-dates/lib/css/_datepicker.css';
import { DateRangePicker } from 'react-dates';

export default function DatePicker() {
    const [startDate, setStartDate] = useState(null);
    const [endDate, setEndDate] = useState(null);
    const [focusedInput, setFocusedInput] = useState(null);

    const setStartAndEndDate = (startDateInput, endDateInput) => {
        setStartDate(startDateInput);
        setEndDate(endDateInput);
    };

    const smallDevice = window.matchMedia('(max-width: 400px)').matches;
    const orientation = smallDevice ? 'vertical' : 'horizontal';

    return (
        <>
            <DateRangePicker
                displayFormat="DD/MM/YYYY"
                startDate={startDate} // momentPropTypes.momentObj or null,
                startDateId="startDate" // PropTypes.string.isRequired,
                endDate={endDate} // momentPropTypes.momentObj or null,
                endDateId="endDate" // PropTypes.string.isRequired,
                onDatesChange={({ startDate, endDate }) => setStartAndEndDate(startDate, endDate)} // PropTypes.func.isRequired,
                focusedInput={focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null,
                onFocusChange={focusedInput => setFocusedInput(focusedInput)} // PropTypes.func.isRequired,
                orientation={orientation}
                withPortal={smallDevice}
                showClearDates
                showDefaultInputIcon
                hideKeyboardShortcutsPanel
            />
        </>
    );
}

标签: reactjsreact-dates

解决方案


如果您不介意探索DayPickerRangeController,我知道关闭日历的两个选项:

  1. 将隐藏日历 UI 的函数传递给onOutsideClick道具。

  2. 在函数中呈现自定义按钮并将该函数作为值传递给renderCalendarInfo道具。

DayPickerRangeController该函数将作为在其render函数中返回 的父组件的成员存在。

函数逻辑可以简单地是用一个有条件地返回方法DayPickerRangeController中的布尔值来更新内部组件状态的逻辑render

示例代码: https ://gist.github.com/osifo/984cd60dce5d6abb49b6923ffa580638


推荐阅读