温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - How to prevent user from selecting date above end date in react-dates
html javascript reactjs date-range airbnb

javascript - 如何防止用户选择反应日期中结束日期以上的日期

发布于 2020-03-27 10:22:33

我想知道如何防止用户选择今天的日期以上的日期。例如,今天是3.7,因此将其设置为用户可以选择的最高结束日期。

<DateRangePicker
    startDate={this.state.startDate} 
    startDateId="startDate" 
    endDate={this.state.endDate} 
    endDateId="endDate" 
    onDatesChange={({ startDate, endDate }) => {
      this.setState({ startDate, endDate }, () => {});
    }} 
    focusedInput={this.state.focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null,
    onFocusChange={focusedInput => this.setState({ focusedInput })} // PropTypes.func.isRequired,
    daySize={50}
    noBorder={true}
    isOutsideRange={() => false}
/>

查看更多

查看更多

提问者
Roxy'Pro
被浏览
286
sergdenisov 2019-07-04 21:45

您应该使用isOutsideRangeprop和Moment.js来处理可用的日期范围。例如,您可以通过这种方式只允许选择过去30天内的日期:

CodeSandbox

import React, { Component } from "react";
import moment from "moment";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
import { DateRangePicker } from "react-dates";
import { START_DATE, END_DATE } from "react-dates/constants";

export default class Dates extends Component {
  state = {
    startDate: null,
    endDate: null,
    focusedInput: null
  };

  onDatesChange = ({ startDate, endDate }) =>
    this.setState({ startDate, endDate });

  onFocusChange = focusedInput => this.setState({ focusedInput });

  isOutsideRange = day =>
    day.isAfter(moment()) || day.isBefore(moment().subtract(30, "days"));

  render() {
    const { startDate, endDate, focusedInput } = this.state;

    return (
      <DateRangePicker
        startDate={startDate}
        startDateId={START_DATE}
        endDate={endDate}
        endDateId={END_DATE}
        onDatesChange={this.onDatesChange}
        focusedInput={focusedInput}
        onFocusChange={this.onFocusChange}
        daySize={50}
        noBorder={true}
        isOutsideRange={this.isOutsideRange}
      />
    );
  }
}