import React, { useState } from 'react' import calendar from 'js-calendar-converter' const j = ['立春', '惊蛰', '清明', '立夏', '芒种', '小暑', '立秋', '白露', '寒露', '立冬', '大雪', '小寒'] const News = () => { const formatDate = (date) => { const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const lunarDate = calendar.solar2lunar(year, month, day) console.log(lunarDate) return `${year}年${month}月${day}日 ${hour}时${minute}分` } const handleConfirm = (val) => { formatDate(val) } return ( <div> <DatePicker onConfirm={handleConfirm} /> </div> ) } 以上代码里,变量j里的内容为十二节气。 打印lunarDate结果显示有很多参数,包括参数Term代表某一节气的名称,参数cYear代表当前选中的阳历年份,参数cMonth代表当前选中的阳历月份,cDay代表当前选中的阳历日期,参数date代表当前选中的阳历年月日。 使用react、es6语法和Hook修改以上代码,实现以下效果:当在DatePicker里选中任意一天后,打印出该天所在当月的节气日、上个月节气日和下个月节气日对应的阳历日期。
时间: 2023-12-10 17:39:40 浏览: 120
可以先在组件中定义一个状态`selectedDate`,用来保存选中的日期。然后在`handleConfirm`函数中更新该状态,并计算出所在当月的节气日、上个月节气日和下个月节气日对应的阳历日期。
代码如下:
```
import React, { useState } from 'react'
import calendar from 'js-calendar-converter'
import DatePicker from './DatePicker'
const j = ['立春', '惊蛰', '清明', '立夏', '芒种', '小暑', '立秋', '白露', '寒露', '立冬', '大雪', '小寒']
const News = () => {
const [selectedDate, setSelectedDate] = useState(null)
const formatDate = (date) => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
return `${year}年${month}月${day}日`
}
const getJieQiDate = (year, month, jieQi) => {
const jieQiIndex = j.indexOf(jieQi)
const prevMonth = month === 1 ? 12 : month - 1
const prevYear = prevMonth === 12 ? year - 1 : year
const nextMonth = month === 12 ? 1 : month + 1
const nextYear = nextMonth === 1 ? year + 1 : year
const prevJieQi = j[jieQiIndex - 1 < 0 ? 11 : jieQiIndex - 1]
const nextJieQi = j[jieQiIndex + 1 > 11 ? 0 : jieQiIndex + 1]
const jieQiDate = new Date(calendar.getTerm(year, jieQiIndex * 2))
const prevJieQiDate = new Date(calendar.getTerm(prevYear, jieQiIndex * 2 - 2))
const nextJieQiDate = new Date(calendar.getTerm(nextYear, jieQiIndex * 2 + 2))
return {
jieQiDate: formatDate(jieQiDate),
prevJieQiDate: formatDate(prevJieQiDate),
nextJieQiDate: formatDate(nextJieQiDate),
prevJieQi,
nextJieQi
}
}
const handleConfirm = (val) => {
setSelectedDate(val)
const year = val.getFullYear()
const month = val.getMonth() + 1
const { jieQiDate, prevJieQiDate, nextJieQiDate, prevJieQi, nextJieQi } = getJieQiDate(year, month, j[0])
console.log(`${month}月节气:${j[0]},日期:${jieQiDate}`)
console.log(`上个月节气:${prevJieQi},日期:${prevJieQiDate}`)
console.log(`下个月节气:${nextJieQi},日期:${nextJieQiDate}`)
}
return (
<div>
<DatePicker onConfirm={handleConfirm} />
{selectedDate && <p>已选日期:{formatDate(selectedDate)}</p>}
</div>
)
}
export default News
```
其中`getJieQiDate`函数用来计算节气日和对应阳历日期,它接收当前选中日期所在的年份、月份和节气名称作为参数,返回一个包含节气日和阳历日期的对象。
在`handleConfirm`函数中,我们先更新`selectedDate`状态,然后调用`getJieQiDate`函数计算出节气日和阳历日期,并打印出来。
最后在组件中渲染出已选日期,方便查看。
阅读全文