// 自定义时间组件 import React, { useEffect, useMemo, useState } from 'react' import { DatePicker, Select } from 'antd' import moment from 'moment' import locale from 'antd/lib/date-picker/locale/zh_CN' const DateTime = (props) => { const { value, onChange, schema, addons } = props const { disabled, format, presetValue, placeholder, options, currentDate, defaultCurrent, formDisabled, } = schema const period = useMemo(() => { let hour = moment().hour() if (value && moment(value)._isValid) { hour = moment(value).hour() } return hour < 12 ? '上午' : '下午' }, [value]) useEffect(() => { if (addons) { let value = presetValue if (!formDisabled && options === '默认为当前时间') { if (disabled) { if (!presetValue) { value = moment(new Date()).format('YYYY-MM-DD HH:mm:ss') } } else { value = moment(new Date()).format('YYYY-MM-DD HH:mm:ss') } } addons.setValue(addons.dataPath, value) } else { onChange(presetValue) } }, [presetValue, options, formDisabled, disabled]) const disabledDate = (current) => { if (options === '不超过当前时间') { return current && current > moment() } else { return false } } const dateChange = (date, dateStr) => { if (date && date._d) { if (format === 'datePeriod') { onChange(moment(date._d).format('YYYY-MM-DD 09:00:00')) } else { onChange(moment(date._d).format('YYYY-MM-DD HH:mm:ss')) } } else { onChange('') } } const selectChange = (date) => { const isValid = moment(value)._isValid if (isValid) { onChange(`${moment(value).format('YYYY-MM-DD')} ${date === '上午' ? '09:00:00' : '13:30:00'}`) } else { onChange(`${moment().format('YYYY-MM-DD')} ${date === '上午' ? '09:00:00' : '13:30:00'}`) } } const isValid = moment(value)._isValid const timeOtions = format === 'dateTime' ? { showTime: { minuteStep: 5, format: 'HH:mm' }, format: 'YYYY-MM-DD HH:mm' } : { picker: format, showTime: false } return ( <div style={{ display: 'flex' }}> <DatePicker disabledDate={disabledDate} disabled={disabled} placeholder={disabled ? (placeholder || '') : (placeholder || '点击选择日期')} value={isValid ? moment(value) : null} onChange={dateChange} showNow {...timeOtions} style={{ width: '100%' }} locale={locale} /> { format === 'datePeriod' && ( <Select disabled={disabled} value={period} style={{ width: '70px' }} onChange={(value) => selectChange(value)} > <Select.Option value='上午'>上午</Select.Option> <Select.Option value='下午'>下午</Select.Option> </Select> ) } </div> ) }; export default DateTime