index.tsx 1.7 KB
import React from 'react';
import { FormItem, DatePicker } from '@formily/antd-v5';
import { Field } from '@formily/react';
import cx from 'classnames';
import './index.less';
import { FieldProps } from '../../typings';
import moment from 'moment';

const { RangePicker } = DatePicker;
const RangePickerWrap = (props: any) => {
  const { value, onChange, unix } = props;

  const [stateValue, setStateValue] = React.useState<any>([]);

  React.useEffect(() => {
    if (value && value.length && unix) {
      setStateValue([moment(value[0] * 1000), moment(value[1] * 1000)]);
      return;
    }

    setStateValue(value);
  }, [value]);

  const handleChange = (value: any) => {
    const [start, end] = value || [];

    if (!value) {
      onChange([]);
      return;
    }
    if (unix) {
      onChange([moment(start).unix(), moment(end).unix()]);
    } else {
      onChange(value);
    }
  };

  return <RangePicker {...props} onChange={handleChange} value={stateValue} />;
};

const RangeDate: React.FC<FieldProps> = (props) => {
  const { name, title, validator = [], format, decoratorProps, componentProps } = props;

  return (
    <div className={cx('global_rangedate')}>
      <Field
        {...props}
        name={name}
        title={title}
        decorator={[
          FormItem,
          {
            ...decoratorProps,
          },
        ]}
        component={[
          RangePickerWrap,
          {
            allowClear: true,
            componenttypename: 'DatePicker.RangePicker',
            format: format || ['YYYY/MM/DD', 'YYYY/MM/DD'],
            ...componentProps,
          },
        ]}
        validator={validator}
      />
    </div>
  );
};

export default RangeDate;