【发布时间】:2019-09-28 12:51:44
【问题描述】:
我正在尝试使用库 day-picker 为输入范围日期选择器创建一个 React 无状态组件。
如果我尝试将有状态组件转换为无状态,则无法访问 this 关键字,因为无状态组件没有 this 的范围。
我对 React 和 Hooks 非常陌生,并尽我所能解决,但不知何故未能解决问题,这就是我正在尝试的。
问题 - 日期选择器范围输入未按预期工作。日历显示始终从当前月份开始。但不知何故,它是从去年开始的。
import React, { useState } from 'react';
import DayPickerInput from 'react-day-picker/DayPickerInput';
import moment from 'moment';
import { formatDate, parseDate } from 'react-day-picker/moment';
import 'react-day-picker/lib/style.css';
const DayPickerRange = () => {
const [days, setDays] = useState({
from: new Date(),
to: new Date(today.getTime() + 24 * 60 * 60 * 1000)
});
function showFromMonth() {
const { from, to } = days;
if (!from) {
return;
}
if (moment(to).diff(moment(from), 'months') < 2) {
// this.to.getDayPicker().showMonth(from);
to.getDayPicker().showMonth(from);
}
}
const handleFromChange = from => {
// Change the from date and focus the "to" input field
setDays({ from, to }, showFromMonth);
};
const handleToChange = to => {
setDays({ from, to });
};
const { from, to } = days;
const modifiers = {
start: from,
end: to
};
return (
<div className="InputFromTo">
<DayPickerInput
value={from}
placeholder="From"
format="LL"
formatDate={formatDate}
parseDate={parseDate}
dayPickerProps={{
utc: true,
selectedDays: [from, { from, to }],
disabledDays: [{ before: new Date() }],
toMonth: to,
month: to,
modifiers,
numberOfMonths: 12,
onDayClick: () => to.getInput().focus()
}}
onDayChange={handleFromChange}
/>
<span className="InputFromTo-to">
<DayPickerInput
ref={el => {
days.to = el;
}}
value={to}
placeholder="To"
format="LL"
formatDate={formatDate}
parseDate={parseDate}
dayPickerProps={{
selectedDays: [from, { from, to }],
disabledDays: [{ before: new Date() }],
modifiers,
month: from,
fromMonth: from,
numberOfMonths: 12,
utc: true
}}
onDayChange={handleToChange}
/>
</span>
</div>
);
};
export default DayPickerRange;
【问题讨论】:
-
可能这只是在
showFromMonth方法中使用旧版本的days的问题,因为那是使用当前版本的days,而handleFromChange将收到下一个from的版本。 -
@HenryWoody - 感谢您的回复,请您帮忙处理一下 sn-p
-
只是组件第一次挂载时年份错误的问题吗?或者如果您选择另一个日期仍然是错误的?
-
嗨用户,检查我的解决方案,如果有帮助,请告诉我。