详细的写了一个日历组件,把遇到的问题整理在这里
一开始打算用 antDesign 的日历组件稍作修改,但我要完成的日历组件需要周日历,现在 antD 没有这个功能,所以只好自己写一个
antd 的日历组件显示中文
import locale from 'antd/lib/calendar/locale/zh_CN.js'
<Calendar
fullscreen={false}
onPanelChange={this.onPanelChange}
locale={locale}
/>
自写日历
在网上查找了很多人写的日历,最后参考了这位大佬的写法 https://blog.csdn.net/liuyuhua666 链接中有几个小地方代码打错了,都是这个方法里的,我还给改成了周日到周六的显示:
getDayText(line, weekIndex, weekDay, monthDays, mode) {
let year = this.state.year;
let month = this.state.month;
let _weekDay = weekDay;
if (weekDay === 0) {
_weekDay = 7;
}
let number;
if (mode === 'month') {
number = line * 7 + weekIndex - _weekDay + 1;
if (number <= 0 ) {
if (month === 0) {
year = year - 1;
month = 11;
} else {
month = month - 1;
}
let preMonthDays = CalenderUtil.getCurrentMonthDays(year, month);
number = preMonthDays + number;
} else if (number > monthDays) {
if (month === 11) {
year = year + 1;
month = 0;
} else {
month = month + 1;
}
number = number - monthDays;
}
} else {
const day = this.state.day;
number = line * 7 + weekIndex - _weekDay + day;
if (number > monthDays && number <= (day + 6)) {
if (month === 11) {
year = year + 1;
month = 0;
} else {
month = month + 1;
}
number = number - monthDays;
} else if (number < day || number > (day + 6)) {
return '';
}
}
return year + '-' + month + '-' + number;
}
其他就是样式细节的调整,改完之后的效果图:
农历
使用 solarLunar 库
import solarLunar from 'solarLunar';
自定义方法(节气,节日): ps: 注意除夕是春节的前一天而不是腊月三十,比如今年就没有腊月三十
getlunarDayCn = (year_, month_, day_) => {
let lunar = solarLunar.solar2lunar(year_, month_ + 1, day_);
let JudgeLunar = solarLunar.solar2lunar(year_, month_ + 1, day_ + 1);
let { isTerm, term, monthCn, dayCn, cMonth, cDay, ncWeek } = lunar
let showDay = isTerm ? term : dayCn;
if (showDay === '初一') {
showDay = monthCn
}
if (JudgeLunar.monthCn === '正月' && JudgeLunar.dayCn === '初一') return '除夕';
const lunarFestivalMap = {
'正月_初一' : '春节',
'正月_十五' : '元宵节',
'五月_初五' : '端午节',
'七月_初七' : '七夕节',
'八月_十五' : '中秋节',
'九月_初九' : '重阳节'
}
const solarFestivalMap = {
'1.1' : '元旦',
'3.8' : '妇女节',
'5.1' : '劳动节',
'5.4' : '青年节',
'6.1' : '儿童节',
'7.1' : '建党节',
'8.1' : '建军节',
'9.10': '教师节',
'10.1': '国庆节',
'12.25': '圣诞节'
}
const lunarFestival = lunarFestivalMap[`${monthCn}_${dayCn}`];
const solarFestival = solarFestivalMap[`${cMonth}.${cDay}`];
if(cMonth === 5 && cDay > 7 && cDay < 15 && ncWeek === '星期日') return '母亲节';
if(cMonth === 6 && cDay > 14 && cDay < 22 && ncWeek === '星期日') return '父亲节';
return lunarFestival ? lunarFestival : solarFestival ? solarFestival : showDay;
}
效果图:
|