React 的 DateRangePicker 中的最大天数限制如何?

Posted

技术标签:

【中文标题】React 的 DateRangePicker 中的最大天数限制如何?【英文标题】:How Maximum days restriction in DateRangePicker for the React? 【发布时间】:2022-01-20 23:37:40 【问题描述】:

如何在DateRangePicker 中实现 React 的最大天数限制?

【问题讨论】:

【参考方案1】:

我已尝试解决以下要求。如果有人觉得这很有用,请分享,

这会将 startDate 范围之前和之后的选择限制为 maxDays。

import React, useState, useEffect from "react"
import makeStyles from "@material-ui/core/styles";
import  DateRangePicker  from 'react-date-range';
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css';
import  addDays, subDays  from "date-fns"; // theme css file


const useStyles = makeStyles(theme => (
  root:
    // padding: 16
  
))

const selectionRange = 
  startDate: new Date(),
  endDate: new Date(),
  key: 'dateRange',


const DateRange = (props) => 
  const classes = useStyles();
  const 
    dateRange, 
    onSelectPeriod, 
    hides, 
    minDate, 
    maxDate,
    maxDays
   = props
  const [period, setPeriod] = useState(selectionRange)
  const [miDate, setMiDate] = useState(new Date(1970, 1, 1))
  const [maDate, setMaDate] = useState(new Date(2100, 1, 1))
 
  useEffect(()=>
    if(dateRange) 
      setPeriod(dateRange)
     
    
    if(hides)
      hides.map((num, index) => 
        (document.getElementsByClassName('rdrStaticRanges')[0]).childNodes[num-index].remove();
      )

    if(minDate != null) setMiDate(minDate)
    if(maxDate != null) setMaDate(maxDate)
  ,[])

  useEffect(()=>
    onSelectPeriod(period)
  ,[period])

  const handleSelect = (ranges) => 
    if(ranges === undefined) return
    // console.log("DateRangePicker: ", ranges)    
    setPeriod(ranges.dateRange)

    // set to restrict only maxDays range selection; post selection it reset to as initial for further selection
    if(maxDays != null) 
      if(ranges.dateRange.startDate.getTime() === ranges.dateRange.endDate.getTime())
        // REstrict maxDays before or after for selection
        setMiDate(subDays(ranges.dateRange.startDate, maxDays-1))
        const mDate = addDays(ranges.dateRange.startDate, maxDays-1)
        if(mDate.getTime() <= maxDate.getTime()) setMaDate(mDate)
       else 
        // RESET as INITIAL
        if(minDate != null) 
          setMiDate(minDate) 
         else 
          setMiDate(new Date(1970, 1, 1))
        

        if(maxDate != null) 
          setMaDate(maxDate)
         else 
          setMaDate(new Date(2100, 1, 1))
        
      
    
  

  return (
    <div className=classes.root>
      <DateRangePicker
        ranges=[period]
        onChange=handleSelect
        minDate=miDate
        maxDate=maDate
      />
    </div>
  )


export default DateRange

【讨论】:

以上是关于React 的 DateRangePicker 中的最大天数限制如何?的主要内容,如果未能解决你的问题,请参考以下文章

React 的 DateRangePicker 中的最大天数限制如何?

daterangepicker关闭父引导下拉列表

daterangepicker 使用方法总结

daterangepicker 使用说明+参数详解

关于daterangepicker的配置

React bootstrap datepicker - 自定义