如何在蚂蚁设计日期选择器中禁用所有星期日和特定日期的数组

时间:2020-07-23 09:35:58

标签: reactjs datepicker antd

以下代码禁用了所有以前的日期,包括今天,但是我想禁用所有的星期日和蚂蚁设计日期选择器中的特定日期数组。

< DatePicker size = "large"
  format = "DD/MM/YYYY"
  nChange = {
    this.onDate1Change
  }
  disabledDate = {
    current => {
      return current && current < moment().endOf('day');
    }
  }
/>

1 个答案:

答案 0 :(得分:2)

首先,我们来看看依赖的example中antd的Datepicker docs

  1. 禁用所有星期日

我们使用moment.js库检查日期并禁用所有星期日(这里是第一个==零)。

例如:

function disabledDate(current) {
  // Can not select sundays and predfined days
  return moment(current).day() === 0 
}
  1. 禁用特定日期

首先,我们定义一个日期数组,然后检查转换后的日期是否在禁用的数组中。

const disabledDates = ["2020-07-21", "2020-07-23"];

function disabledDate(current) {
  // Can not select Sundays and predefined days
  return disabledDates.find(date => date === moment(current).format("YYYY-MM-DD"));
}
  1. 放在一起

现在,我们可以结合两种解决方案。一个有效的示例可以在this CodeSandbox中找到。

例如:

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import moment from "moment";
import { DatePicker } from "antd";

const disabledDates = ["2020-07-21", "2020-07-23"];

function disabledDate(current) {
  // Can not select Sundays and predefined days
  return (
    moment(current).day() === 0 ||
    disabledDates.find(date => date === moment(current).format("YYYY-MM-DD"))
  );
}

ReactDOM.render(
  <>
    <DatePicker
      format="YYYY-MM-DD HH:mm:ss"
      disabledDate={disabledDate}
      showTime={{ defaultValue: moment("00:00:00", "HH:mm:ss") }}
    />
  </>,
  document.getElementById("container")
);