首先我们来看看 antd 的 Datepickerexample https://codesandbox.io/s/yjegy在依赖的docs https://ant.design/components/date-picker/#components-date-picker-demo-disabled-date.
- 禁用所有周日
我们使用moment.js https://momentjs.com/lib 检查日期并禁用所有星期日(这里是第一个 == 零)。
E.g.:
function disabledDate(current) {
// Can not select sundays and predfined days
return moment(current).day() === 0
}
- 禁用特定日期
首先,我们定义一个日期数组,然后检查转换后的日期是否在禁用数组中。
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"));
}
- 将所有内容放在一起
现在我们可以结合这两种解决方案。可以在以下位置找到一个工作示例这个代码沙盒 https://codesandbox.io/s/infallible-goldberg-1n30p?file=/index.js.
E.g.:
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")
);