timePicker.tsx 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { Radio, DatePicker } from 'antd';
  2. import type { DatePickerProps } from 'antd';
  3. import moment from 'moment';
  4. import { useEffect, useState } from 'react';
  5. export enum TimeKey {
  6. 'today' = 'today',
  7. 'week' = 'week',
  8. 'month' = 'month',
  9. 'year' = 'year',
  10. }
  11. export type TimeType = keyof typeof TimeKey;
  12. interface ExtraTimePickerProps extends Omit<DatePickerProps, 'onChange' | 'value'> {
  13. onChange?: (value: number[]) => void;
  14. value?: number[];
  15. defaultTime?: TimeType;
  16. }
  17. export const getTimeByType = (type: TimeType) => {
  18. switch (type) {
  19. case TimeKey.week:
  20. return moment().subtract(6, 'days').valueOf();
  21. case TimeKey.month:
  22. return moment().startOf('month').valueOf();
  23. case TimeKey.year:
  24. return moment().subtract(365, 'days').valueOf();
  25. default:
  26. return moment().startOf('day').valueOf();
  27. }
  28. };
  29. export default (props: ExtraTimePickerProps) => {
  30. const [radioValue, setRadioValue] = useState<TimeType | undefined>(undefined);
  31. const { value, onChange, ...extraProps } = props;
  32. const change = (startTime: number, endTime: number) => {
  33. if (onChange) {
  34. onChange([startTime, endTime]);
  35. }
  36. };
  37. const timeChange = (type: TimeType) => {
  38. const endTime = moment(new Date()).valueOf();
  39. const startTime: number = getTimeByType(type);
  40. setRadioValue(type);
  41. change(startTime, endTime);
  42. };
  43. useEffect(() => {
  44. timeChange(props.defaultTime || TimeKey.today);
  45. }, []);
  46. return (
  47. <>
  48. {
  49. // @ts-ignore
  50. <DatePicker.RangePicker
  51. {...extraProps}
  52. value={
  53. value && [
  54. moment(value && value[0] ? value[0] : new Date()),
  55. moment(value && value[1] ? value[1] : new Date()),
  56. ]
  57. }
  58. onChange={(rangeValue) => {
  59. setRadioValue(undefined);
  60. if (rangeValue && rangeValue.length === 2) {
  61. change(rangeValue[0]!.valueOf(), rangeValue[1]!.valueOf());
  62. }
  63. }}
  64. renderExtraFooter={() => (
  65. <div style={{ padding: '12px 0' }}>
  66. <Radio.Group
  67. defaultValue="day"
  68. buttonStyle="solid"
  69. value={radioValue}
  70. onChange={(e) => {
  71. timeChange(e.target.value);
  72. }}
  73. >
  74. <Radio.Button value={TimeKey.today}>当天</Radio.Button>
  75. <Radio.Button value={TimeKey.week}>近一周</Radio.Button>
  76. <Radio.Button value={TimeKey.month}>近一月</Radio.Button>
  77. <Radio.Button value={TimeKey.year}>近一年</Radio.Button>
  78. </Radio.Group>
  79. </div>
  80. )}
  81. />
  82. }
  83. </>
  84. );
  85. };