首页 > 解决方案 > 反应日期选择器处理空日期和时间值

问题描述

我在反应中有带有时间组件的日期选择器,它可以有空值或空值日期。

 <DatePicker selected={fromDttm} timeInputLabel="Time:" name="from_dttm" id="from_dttm" className="form-control" onChange={date => setFromDtttm(date)} dateFormat="dd/MM/yyyy h:mm aa" showTimeInput />

宣言

  const [fromDttm, setFromDtttm] = useState(new Date());
  const [toDttm, setToDttm] = useState(new Date());

此代码在有有效日期值时有效,但在没有日期值时出现错误。只有我使用时间showTimeInput参数才会发生这种情况。当只有没有时间的日期时,我没有问题。

低于错误。

   RangeError: Invalid time value
format
E:/fuel-man-workspace/fuelman-frontend/fuel-man-ui/node_modules/date-fns/esm/format/index.js:371
  368 | var originalDate = toDate(dirtyDate);
  369 | 
  370 | if (!isValid(originalDate)) {
> 371 |   throw new RangeError('Invalid time value');
      | ^  372 | } // Convert the date in system timezone to the same date in UTC+00:00 timezone.
  373 | // This ensures that when UTC functions will be implemented, locales will be compatible with them.
  374 | // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376

我不知道为什么反应日期选择器不接受带有时间分量的日期字段的空值。有没有办法处理这个。如果变量没有值,我需要显示空输入fromDTTM

标签: reactjsdatepicker

解决方案


推荐阅读