如何防止用户选择反应日期中结束日期以上的日期 [英] How to prevent user from selecting date above end date in react-dates

查看:107
本文介绍了如何防止用户选择反应日期中结束日期以上的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering how I could prevent a user from selecting dates above today's date. For example, today is 3.7 so let that be the highest end date a user could select.

<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}
/>


推荐答案

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

You should use an isOutsideRange prop and Moment.js for working with available dates ranges. For example, you can allow selecting only dates within a past 30 days this way:

代码沙盒

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}
      />
    );
  }
}

这篇关于如何防止用户选择反应日期中结束日期以上的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆