自定义 年-月-日 组件
code
import { useState } from 'react'
function Year_Month_Date() {
const [yearList, setYearList] = useState([])
const [monthList, setMonthList] = useState([])
const [dateList, setDateList] = useState([])
const [currentYear, setCurrentYear] = useState((new Date()).getFullYear())
const [currentMonth, setCurrentMonth] = useState((new Date()).getMonth() + 1)
const [currentDate, setCurrentDate] = useState((new Date()).getDate())
const computedTime = new Date(`${currentYear}-${currentMonth}-${currentDate}`)
useEffect(() => {
// 时间
console.log(computedTime)
}, [currentYear, currentMonth, currentDate])
// 年
const renderYearList = () => {
const _currentYear = (new Date()).getFullYear()
const years = []
for(let i = _currentYear - 80; i <= _currentYear + 20; i++) {
years.push(i)
}
setYearList(years)
}
// 月
const renderMonthList = () => {
const months = []
for(let i = 1; i < 13; i++) {
months.push(i)
}
setMonthList(months)
}
// 日
const renderDateList = (year, month) => {
const dates = []
const currentMonthDateCount = (new Date(year, month, 0)).getDate()
for(let i = 1; i <= currentMonthDateCount; i++) {
dates.push(i)
}
setDateList(dates)
}
// 年月固定
useEffect(() => {
renderYearList()
renderMonthList()
}, [])
// 每个月多少天根据选择的年月计算
useEffect(() => {
renderDateList(currentYear, currentMonth)
}, [currentYear, currentMonth])
return (
<>
<Flex>
{/*
年
*/}
<SelectField
label="Year"
labelHidden
value={currentYear}
onChange={(e) => {setCurrentYear(e.target.value)}}
>
{
yearList.map(item => <option key={item} value={item}>{item} {intl.get("YEAR")}</option>)
}
</SelectField>
{/*
月
*/}
<SelectField
label="month"
labelHidden
value={currentMonth}
onChange={(e) => {setCurrentMonth(e.target.value)}}
>
{
monthList.map(item => <option key={item} value={item}>{item} {intl.get("_MONTH")}</option>)
}
</SelectField>
{/*
日
*/}
<SelectField
label="date"
labelHidden
value={currentDate}
onChange={(e) => {setCurrentDate(e.target.value)}}
>
{
dateList.map(item => <option key={item} value={item}>{item} {intl.get("_DATE")}</option>)
}
</SelectField>
</Flex>
</>
)
}
如图: