reactjs - 使用 DateRangePicker 阻止特定月份中的某一天

标签 reactjs react-dates

使用 react-dates 中的 DateRangePicker ,我希望禁用星期一,但仅限于七月和八月。 React 对我来说是新的,我不知道如何开始解决这个问题。

该文档有 blockedDays prop,但我不清楚应该如何将它用于我的特定情况。

如何访问当前显示的月份以及如何随后阻止星期一?

对于那些希望查看我的代码的人,我制作了 gist .

最佳答案

您可以使用 isDayBlocked 属性来实现此目的。

此 Prop 是一个函数回调,它将向您发送 moment date ,并要求您发回一个 bool 值,true 表示该天被阻止,false 表示相反。

根据moment documentation ,以下是您如何知道是否应该阻止您的一天的方法:

isDayBlocked = momentDate => {
    if (momentDate.format('ddd') === 'Mon' && ['Jul', 'Aug'].includes(momentDate.format('MMM')) return true

    return false
}

以下条件也适用(请参阅上面的文档链接):

momentDate.format('d') === 0 && [6, 7].includes(momentDate.format('M')

简短语法:

isDayBlocked = momentDate => momentDate.format('d') === 0 && [6, 7].includes(momentDate.format('M')

这是选择器:

<DateRangePicker
    isDayBlocked={this.isDayBlocked}
    // ... your other props
/>

我想我找到了。在您给我的代码中,您声明了 isDayBlocked 属性两次:

            isDayBlocked={day1 => this.state.disabledDates.some(day2 => isSameDay(day1, day2))} //First time
            startDateId="datePickerStart"
            endDateId="datePickerEnd"
            onDatesChange={this.onDatesChange}
            onFocusChange={this.onFocusChange}
            focusedInput={focusedInput}
            startDate={startDate}
            endDate={endDate}
            minimumNights={minimumNights}
            isOutsideRange={condition}
            isDayBlocked = {momentDate => momentDate.format('d') === 0 } // Second one

您可以将它们合并到一个函数中,如我的第一段代码所示,并将两个条件放入其中:

isDayBlocked = momentDate => {
    if (momentDate.format('ddd') === 'Mon' && ['Jul', 'Aug'].includes(momentDate.format('MMM')) return true

    if(this.state.disabledDates.some(day2 => isSameDay(day1, day2))) return true

    return false
}

根据您的评论,您有 2 个解决方案。

将要测试的值转换为字符串:

momentDate => momentDate.format('d') === '0' && ['6','7'].includes(momentDate.format('M')

或者使用非严格运算符:

momentDate => momentDate.format('d') == 0 && ['6', '7'].includes(momentDate.format('M')

关于reactjs - 使用 DateRangePicker 阻止特定月份中的某一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54134458/

相关文章:

reactjs - 如何在 Gatsby 中查询特定语言的 markdown 文件?

javascript - 从日历中选择单个日期的 react 日期解决方案

javascript - 如何防止用户在 react 日期中选择高于结束日期的日期

javascript - react-dates 组件不允许选择当前日期之前的日期

reactjs - Next.js 域路由与子域

reactjs - 在ComponentDidUpdate中显示错误 react native 和Redux

reactjs - 解析 JSON babel 失败时出错

javascript - React中的RBAC,如何实现,构想?

reactjs - 使用react-with-style来设置react-dates组件的样式

javascript - 适合移动设备的 Airbnb react 日期库的配置