typescript 日历月计数器React

sxissh06  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(158)

我正在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

svmlkihl

svmlkihl1#

简单的修复,只需要使用<=>=而不是<>。这是因为如果 * 当前 * 月份已经是1月或12月,而不是已经过了1月或12月,那么您需要更改年份。

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);
        }
    };

Live demo (will probably be broken when I delete the fork)

相关问题