next.js React-Calendar,如何禁用一个月内的日期?

e5nszbig  于 2023-06-05  发布在  React
关注(0)|答案(1)|浏览(381)

我想在日历中禁用所选日期。我修改了它,但问题是当我在五月禁用日期时,它将在所有月份禁用它。例如:如果我在五月禁用第四天,它将禁用所有月份的第四天。我还看到了这个链接:how to disable some dates in react-calendar我该如何解决这个问题。谢谢

let disableDates = ''
  let date1 = ''

  let selectedDays = []
  let disable = []
  
  const handleClick = (date) => {

     disableDates = new Date(date)
     date1=disableDates.getDate()
     
     disable.push(date1)
     console.log(disable)  //(2) [2, 3]

     selectedDays.push(date)
    console.log('selectedDays', selectedDays)  //(2) [Fri Jun 02..., Sat Jun...]

  }

ReactCalendar在这里:

<ReactCalendar 
      minDate={new Date()}
     // tileDisabled={({date}) => date.getDate()===date1}
      tileDisabled={({date}) => disable.includes(date.getDate()) }
      onClickDay={handleClick} 
       
       />
plupiseo

plupiseo1#

这是因为您使用相同的disable数组来存储所有月份的禁用日期。要解决这个问题,请尝试为每个月分离disable数组:

let disabledDates = {};

const handleClick = (date) => {
  const selectedDate = new Date(date);
  const month = selectedDate.getMonth();

  const disabledMonthDates = disabledDates[month] || [];
  const selectedDay = selectedDate.getDate();

  if (!disabledMonthDates.includes(selectedDay)) {
    disabledMonthDates.push(selectedDay);
  } else {
    const index = disabledMonthDates.indexOf(selectedDay);
    disabledMonthDates.splice(index, 1);
  }
  disabledDates[month] = disabledMonthDates;
  console.log(disabledDates);
};
  • ReactCalendar:
<ReactCalendar
minDate={new Date()}
tileDisabled={({ date }) =>
  disabledDates[date.getMonth()]?.includes(date.getDate())
}
onClickDay={handleClick}
/>

相关问题