vben框架antd RangePicker设置不可选项为三个月

思路:
1、使用openChange、calendarChange获取当前选中时间;
2、计算不可选范围。

输入框配置项代码如下:

// 默认选择当前月
const rangeThisMonth = () => {
  const start = moment().startOf('month').format('YYYY-MM-DD');
  const end = moment().format('YYYY-MM-DD');
  return [start, end];
}

// 配置输入框
const formSchema = [
...
{
    field: 'dateTime',
    label: '时间',
    component: 'RangePicker',
    componentProps: ({ formActionType }) => {
      return {
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD',
        mode: ['date', 'date'],
        placeholder: ['开始日期', '结束日期'],
        defaultValue: rangeThisMonth(),
        onOpenChange: async (_e: any) => {
          const { getFieldsValue } = formActionType;
          const { dateTime } = getFieldsValue();
          checkedDate = dateTime ?? rangeThisMonth();
        },
        onCalendarChange: async (_e: any) => {
          checkedDate = _e;
        },
        disabledDate: (current: moment.Moment) => {
          if (!current || !checkedDate || checkedDate.length == 0 ) {
            return false;
          }

          // checked存在起终
          if (checkedDate && checkedDate.length == 2) {
            // 开始时间大于checkedDate[1]-3个月 结束时间小于checkedDate[0]-3个月
            const timeRange = 
            current < moment(checkedDate[0]).subtract(3, 'month') || 
            current > moment(checkedDate[1]).add(3, 'month');
            return timeRange;
          }
          // checked存在起不存在终
          if (checkedDate && checkedDate.length == 1) {
            // 开始时间大于checkedDate[0]-3个月 结束时间小于checkedDate[0]-3个月
            const timeRange = 
            current < moment(checkedDate[0]).subtract(3, 'month') || 
            current > moment(checkedDate[0]).add(3, 'month');
            return timeRange;
          }
        }, 
      };
    },
  },
...
]

在列表搜索表单中使用此配置,发现点击重置按钮时,会有以下问题:
1、若此选择框数据有重新选择或清除,defaultValue会为null;
2、在配置文件中使用表单方法setFieldsValue也无法赋值;
3、页面useTable方法的配置项formConfig使用resetFunc方法再次调用setFieldsValue可以赋值,但会出现报错,导致无法获取接口。

综上,找到以下解决方法:
1、新增变量判断是否点击重置按钮;
2、页面useTable方法的配置项formConfig在resetFunc改变变量值;
3、在参数处理函数beforeFetch中判断是否点击重置按钮或清空时间选择框;
4、根据3的判断重新调用setFieldsValue赋值。
代码如下:

// 判断是否点击的重置按钮 处理表单重置赋值的报错-暂时未解决
let ifReset = false;
// 列表数据
const [registerTable, { getForm }] = useTable({
  ...
  formConfig: {
    ...
    resetFunc: async () => {
      ifReset = true;
    },
  },
  beforeFetch: (config) => {
    const params = Object.assign({}, config);
    // 时间
    if (ifReset || !params.dateTime) {
      const { setFieldsValue } = getForm();
      // 赋值
      setFieldsValue({
        dateTime: rangeThisMonth(),
      });
      params.dateTime = rangeThisMonth();
      ifReset = false;
    }
    ...
    return params;
  },
  ...
});

以上。

posted @ 2024-05-16 15:55  显示昵称已被使用#  阅读(17)  评论(0编辑  收藏  举报