前言

应公司要求,最近要实现一个日期选择框,只选择年份。并且可以手动设置 上一年 和 下一年。我尝试了几种写法,最后成功了。期间遇到了清空日期后再打开选择日期,值为 NAN ,好在问题都解决了,大概的思路分享给他大家

  1. 引入 DatePicker 组件
<DatePicker onChange={this.handleGetYear} picker="year" className={'datePickerStyle'} value={date ? moment(date,dateString) : null}/>
  1. 在 state 中保存日期状态
  state = {
    dateString:  new Date().getFullYear(),
    date: moment(new Date().getFullYear(), 'YYYY')
  }
  1. 选择年份和修改年份的时候更新状态
// 选择年份
  handleGetYear = (date, dateString) => {
    if (dateString !=='') {
      this.setState({dateString,date: moment(date, dateString)})
    }else {
      this.setState({dateString: '',date: ''})
    }
  }
  // 上一年
  handleGetLastYearClick = () => {
    const last = parseInt(this.state.dateString) - 1
    this.setState({date: moment(last, 'YYYY'),dateString: last})
  }
  // 下一年
  handleGetNextYearClick = () => {
    const next = parseInt(this.state.dateString) + 1
    this.setState({date: moment(next, 'YYYY'),dateString: next})
  }

这里注意: if (dateString !=='') {} 就是为了避免清空日期出现 NAN

同理附上上一月的代码

import React, { Component } from 'react'
import { DatePicker, Table } from 'antd';
import moment from 'moment';
import SearchArea from '../../../../components/Search';
import OwnSelect from '../../../../components/Select'
import OwnButton from '../../../../components/Button/NoIcon'
import OwnIconButton from '../../../../components/Button/HaveIcon';
import searchIcon from '../../../../assets/icon/search.svg';
import exportIcon from '../../../../assets/icon/export.svg'
import '../../../../assets/antd/ant-table.less'
/**
 * 环比分析
 */
export default class SequentialAnalysis extends Component {
  state = {
    params: {
      bdzName: ''
    },
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    // 日期字符串
    dateString: new Date().getFullYear() + '-' + (new Date().getMonth() + 1),
    // 日期 moment
    date: moment((new Date().getFullYear()) + '-' + (new Date().getMonth() + 1), 'YYYY-MM'),
     // 变电站名称数据
     bdzNameOptions: [
      {key: 1, value: '变电站1'},
      {key: 2, value: '变电站2'}
    ],
  }
   // 变电站下拉框
   getSelectedBdzName = data => {
    // 获取当前状态值
    const currentParams = this.state.params
    this.setState({
      params: { ...currentParams, bdzName: data }
    })
  }
  // 选择月份
  handleGetMonth = (date, dateString) => {
    const year = dateString.substring(0, dateString.indexOf('-'))
    const month = dateString.substring(dateString.indexOf('-') + 1, dateString.length)
    if (year !== '' && month !== '') {
      dateString = year + '-' + month
    }
    if (dateString !=='') {
      this.setState({
        dateString ,
        date: moment(date, dateString),
        year,
        month
      }) 
    }else {
      this.setState({dateString: '',date: '',year:'',month:''})
    }
  }
  // 上一月
  handleGetLastMonthClick = () => {
    // 获取年月
    let { month, year, dateString } = this.state
    if (dateString =='') {
      dateString = year + '-' + month
      console.log(dateString);
      this.setState({
        date: moment(dateString, 'YYYY-MM'),
        dateString: dateString,
        year: year,
        month: month,
      })
    }else {
      const last = parseInt(month) == 1 ? (parseInt(year) -1) + '-' + 12 : (parseInt(year)) + '-' + (parseInt(month)-1)
      this.setState({
        date: moment(last, 'YYYY-MM'),
        dateString: last,
        year: parseInt(month) == 1 ? parseInt(year) -1 : year,
        month: parseInt(month) == 1 ? parseInt(12)  : parseInt(month) - 1,
      })
    }
  }
  // 下一月
  handleGetNextMonthClick = () => {
    // 获取年月
    const { month, year, dateString } = this.state
    if (dateString !== '') {
      const next = parseInt(month) == 12 ? (parseInt(year) +1) + '-' + 1 : (parseInt(year)) + '-' + (parseInt(month)+1)// (parseInt(dateString) -1) //parseInt(this.state.dateString)
      this.setState({
        date: moment(next, 'YYYY-MM'),
        dateString: next,
        year: parseInt(month) == 12 ? parseInt(year) +1 : year,
        month: parseInt(month) == 12 ? parseInt(1)  : parseInt(month) + 1,
      })
    }
  }
  // 导出
  handleExportClick = data => {
    console.log('父组件收到了导出指令: ', data);
  }
  // 搜索
  handleSearchClick = data => {
    console.log('父组件收到了搜索指令: ', data);
  }

  render() {
    const { params, bdzNameOptions, date, dateString, year, month } = this.state
    console.log(date,dateString);
    return (
      <div className={'contentStyle'}>
        <SearchArea>
          <span className='spanStyle'>
            日期:
            <DatePicker onChange={this.handleGetMonth} picker="month" className={'datePickerStyle'} value={date ? moment(date,dateString) : null}/>
            <OwnButton value={'上一月'} getYear={this.handleGetLastMonthClick}/>
            <OwnButton value={'下一月'} getYear={this.handleGetNextMonthClick}/>
          </span>
         
          <OwnSelect label={'变电站名称:'} width={'120px'} options={bdzNameOptions} defaultValue={bdzNameOptions[0].key} getSelect={this.getSelectedBdzName}/>
          <OwnIconButton width={'80px'} OwnIcon={exportIcon} value={'导出'} getClick={this.handleExportClick}/>
          <OwnIconButton width={'80px'} OwnIcon={searchIcon} value={'查询'} getClick={this.handleSearchClick}/>
        </SearchArea>
        
        {/* <div className={'dataAreaStyle'}> */}
          <Table 
          />
        {/* </div> */}
      </div>
    )
  }
}

咿呀咿呀哟
16 声望0 粉丝