首页 > 解决方案 > 如何在 React nice dates 中禁用日期?

问题描述

我正在使用来自https://reactnicedates.hernansartorio.com/的日历库。我正在使用<DatePickerCalendar />库中的组件。

我有一个包含三个日期的数组。

[date1, date2, date3]

如何禁用日历中的这三个日期。在该用户的上下文中,无法选择这些日期。在 API 文档中有一个对修改器对象的引用,它需要一个回调来修改日历中的日期,但我正在努力实现这一点。有什么建议吗?谢谢

https://codesandbox.io/s/serverless-dust-vkuhz?file=/src/App.js

标签: javascripthtmlreactjs

解决方案


您需要使用disabled修饰符并对值运行数组循环检查,如下所示:

...
import { isEqual } from "date-fns"; // Importing isEqual to compare dates

const datesArray = [
  new Date(2021, 8, 31, 0, 0, 0, 0),
  new Date(2021, 9, 1, 0, 0, 0, 0),
  new Date(2021, 9, 3, 0, 0, 0, 0)
];

const modifiers = {
  disabled: (date) => {

    // The `some` method will check whether one of the values
    // of the Array passes the test (true):
    const isDisabled = datesArray.some((dateToDisable) =>
      isEqual(dateToDisable, date)
    );

    return isDisabled;

  },
...

其余代码保持原样。

确保datesArray.


推荐阅读