React中Material-UI v0.20.0日历如何禁用特定日期
Alright, let's get your specific date disabling working. You're already on the right track by using the shouldDisableDate prop—we just need to implement the disabledDate method correctly to target the dates you want to block.
First, let's clean up your renderDatePicker method (fixed syntax issues and completed the onChange handler for clarity):
renderDatePicker = ({ input, label, meta: { touched, error }, ...custom }) => { return ( <DatePicker {...input} {...custom} autoOk={true} floatingLabelText={label} dateForm='MM/DD/YYYY' shouldDisableDate={this.disabledDate} minDate={new Date()} value={input.value !== '' ? input.value : null} onChange={(event, value) => input.onChange(value)} errorText={touched && error} /> ); };
Implementing the disabledDate Method
The disabledDate function receives a date object as its parameter and returns true if the date should be disabled (grayed out, unselectable), or false if it's available. Here are a few common scenarios:
Scenario 1: Disable a Fixed List of Specific Dates
Create a set of dates (using ISO format for reliable comparison) and check if the current date is in that set:
// Define your disabled dates (use 'YYYY-MM-DD' format for consistency) const disabledDates = new Set([ '2024-05-15', '2024-05-20', '2024-06-01' ]); disabledDate = (date) => { // Convert the date to an ISO string without time to match our set const dateString = date.toISOString().split('T')[0]; // Return true if the date is in our disabled set return disabledDates.has(dateString); };
Scenario 2: Disable Weekends
If you want to block Saturdays and Sundays:
disabledDate = (date) => { const dayOfWeek = date.getDay(); // 0 = Sunday, 6 = Saturday return dayOfWeek === 0 || dayOfWeek === 6; };
Scenario 3: Combine Multiple Conditions
You can mix and match conditions—for example, disable past dates (already covered by minDate, but included here for completeness), specific dates, and weekends:
const disabledDates = new Set([ '2024-05-15', '2024-05-20' ]); disabledDate = (date) => { const today = new Date(); today.setHours(0, 0, 0, 0); // Reset time to compare dates only const dateString = date.toISOString().split('T')[0]; const dayOfWeek = date.getDay(); // Disable past dates, specific dates, and weekends return date < today || disabledDates.has(dateString) || dayOfWeek === 0 || dayOfWeek === 6; };
Key Notes
- Ensure your
disabledDatemethod is bound correctly (arrow functions like we used here handle binding automatically, so no extra setup needed). - In Material-UI v0.20.0, the
shouldDisableDateprop works exactly as described—returningtruewill disable the target date. - Using ISO strings for date comparison avoids issues with time zones and time components in Date objects.
内容的提问来源于stack exchange,提问作者jay pluto

