react基于antd DatePicker 实现同时展示公历和农历日期pc组件

413 阅读1分钟
  • 实现思想:利用antd dateRender 自定义渲染;
    • 利用current当前时间;
    • 通过getLunarDate.solar2lunar方法获取对应农历信息;
// creat lv
// 2024年-4-10 
// 同时展示公历和农历日期

import React, { Component, useEffect } from 'react';

import { DatePicker, Tooltip } from 'antd';

import moment from 'moment';

//获取@1900-2100区间内的公历、农历互转方法(https://blog.csdn.net/qq_43915356/article/details/110872220)
或者 npm库

import getLunarDate from '@/util/dateswitch';

const lunarFestivalDate = (props) => {
    const { onChange, birthdayDate = {}, viewValue = '' } = props;

    let timeVal = ''
    if (birthdayDate?.date) {
        timeVal = moment(birthdayDate?.date)
    }

    const getRenderDate = (current, today) => {
        const YY = moment(current).format('Y');
        const MM = moment(current).format('M');
        const DD = moment(current).format('D');
        const dateInfo = getLunarDate.solar2lunar(YY, MM, DD);
        const { IDayCn, IMonthCn, festival } = dateInfo;
        let dateM = '';
        if (festival) {//是否为节日
            dateM = festival
        } else {//每月初一显示月份
            dateM = IDayCn === '初一' ? IMonthCn : IDayCn;
        }
        return (
            <>
                <div>
                    {<div className="ant-picker-cell-inner">{moment(current).format('D')}</div>}
                    <div style={{ fontSize: 12 }}>
                        {dateM}
                    </div>
                </div>
            </>
        );
    }

    return (
        <div className='dateCom' style={{ position: 'relative' }}>
        <Tooltip placement="top" title={viewValue}>
            <DatePicker
                placeholder={'请选择时间'}
                allowClear={false}
                value={timeVal}
                // className="lunarCls"
                style={{ width: 202, marginRight:8 }}
                suffixIcon={<i className="iconfont">&#xe736;</i>}
                // getPopupContainer={(node)=>node}
                dateRender={getRenderDate}
                onChange={onChange}
            />

                <div
                    className='dateValue'
                    style={{
                        position: 'absolute',
                        left: 14,
                        top: 8,
                        pointerEvents: 'none',
                        width: 94,
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis'
                    }}
                >{viewValue}</div>
            </Tooltip>
        </div>
    )
}
export default lunarFestivalDate;