react 自定义 年-月-日 组件,单独选择年、月、日,并且产生联动

自定义 年-月-日 组件

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

如图:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值