我正在React中制作日历,在年份之间切换时遇到问题。
const allmonth: string[] = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
const [currentMonthByNum, setcurrentMonthByNum] = React.useState<number>(()=>{
const date = new Date;
return date.getMonth() ;
});
const [currentYear, setCurrentYear] = React.useState<number>(()=>{
const date = new Date;
const curryear = date.getFullYear();
return curryear
});
const [currentMonthDays, setcurrentMonthDays] = React.useState<number>(()=>{
return new Date(currentYear, currentMonthByNum +1, 0).getDate();
})
const [daysInMonth, setDaysInMonth] = React.useState<number[]>([]);
const changeMonthNeg = ()=>{
if( currentMonthByNum < 0){
setcurrentMonthByNum(11)
setCurrentYear(currentYear-1)
}else{
setcurrentMonthByNum(currentMonthByNum - 1)
}
}
const changeMonthPos = ()=>{
if (currentMonthByNum > 11){
setcurrentMonthByNum(0)
setCurrentYear(currentYear+1)
}else{
setcurrentMonthByNum(currentMonthByNum + 1)
}
}
这里的问题是,当我在一月点击向下箭头切换到十二月currentMonthByNum时,如果我将if切换到== 0,则会出现错误,因为0是一月CodeSandBox代码,以便更好地理解:D https://codesandbox.io/s/billowing-sun-05ehk7?file=/src/Calendar.tsx
1条答案
按热度按时间svmlkihl1#
简单的修复,只需要使用
<=
和>=
而不是<
或>
。这是因为如果 * 当前 * 月份已经是1月或12月,而不是已经过了1月或12月,那么您需要更改年份。Live demo (will probably be broken when I delete the fork)