reactjs - 如何在 React JS DateRangePicker 中设置日期范围选择?
问题描述
我在我的 react JS 应用程序中使用“DateRangePicker”组件。我试图将开始日期限制为仅持续 6 个月,开始日期和结束日期之间的差异不应超过 1 个月。我写了以下代码
isOutsideRange = (day) => {
if (day > moment()) return true;
else if (this.state.startDate) {
if (day > moment(this.state.endDate)) return true;
if (day < moment().subtract(6, 'months')) return true;
else return false;
} else if (this.state.endDate) {
if (day > moment(this.state.endDate)) return true;
if ((moment(this.state.endDate) > (moment(this.state.startDate).subtract(1, 'month')))) return true;
else return false;
}
}
这是用户界面代码
<DateRangePicker
startDate={this.state.startDate}
startDateId="validFromDate"
endDate={this.state.endDate}
endDateId="validToDate"
onDatesChange={({ startDate, endDate }) =>
this.handleValidDatesChange(startDate, endDate)
}
focusedInput={this.state.ofrFocusedInput}
onFocusChange={(ofrFocusedInput) => this.setState({ ofrFocusedInput })}
isOutsideRange={(e) => this.isOutsideRange(e)}
showDefaultInputIcon={true}
small={true}
minimumNights={0}
hideKeyboardShortcutsPanel={true}
showClearDates={true}
min={this.maxDate}
shouldDisableDate={({ startDate }) => this.disablePrevDates(startDate)}
// minDate={subDays(new Date(), 10)}
displayFormat={() => "DD/MM/YYYY"}
/>;
我试图调试,但它不工作。有人可以提出解决方案吗?
解决方案
要检查某个时刻是否介于其他两个时刻之间,可以选择查看单位比例(分钟、小时、天等),您应该使用:
moment().isBetween(moment-like, moment-like, String, String);
// where moment-like is Moment|String|Number|Date|Array
例如,如果你需要检查today - 6months <= someDate <= today
,你会使用类似的东西:
// returns TRUE if date is outside the range
const isOutsideRange = date => {
const now = moment();
return !moment(date)
.isBetween(now.subtract(6, 'months'), now, undefined, '[]');
// [] - match is inclusive
}
有关更多详细信息,请查看Is Between docs。这种方法非常灵活,例如,您可以进行独占或包含匹配。
现在,第二个条件。如果你想检查 if endDate - startDate <= 1 month
,你也可以玩一些时刻来实现这一点。
// so if you add 1 month to your startDate and then your end date
// is still before the result or the same - you can say the duration
// between them is 1 month
const lessThanMonth = (startDate, endDate) => {
return endDate.isSameOrBefore(moment(startDate).add(1, 'months'));
}
推荐阅读
- visual-studio-code - 是否可以删除 VScode 中的导航栏按钮?
- react-native - TypeError : props.navigation.getParam 不是函数。In(props.navigation.getParam('name')
- javascript - 如何在我的 html 文档上获得多个幻灯片?
- apex - 如何在 Lightening 数据表中动态添加行或删除行
- sum - 在 pytorch 中,我怎样才能对一些元素求和,并得到一个更小形状的张量?
- algorithm - 给定一个未加权的图,我如何找到具有 1 的生成树。最大叶数 2 最小叶数
- c# - 如何使用 c# 访问和搜索对象列表
- c# - 在运行时在我的应用程序中添加数据源
- python - Python为带有可选符号和小数点的数字构建正则表达式
- node.js - 如何将 useUnifiedtopology 属性添加到 MongoClient 构造函数