问题描述
这是来自 DayPickerRangeController
的 react-dates
组件:
<DayPickerRangeController
startDate={dates.startDate}
endDate={dates.endDate}
onDatesChange={onDatesChange}
focusedInput={focusedInput}
onFocusChange={focusedInput => setFocusedInput(focusedInput)}
numberOfMonths={2}
/>
const [dates,setDates] = useState({ startDate: null,endDate: null });
const [focusedInput,setFocusedInput] = useState(null);
这是changeDates函数:
const onDatesChange = (dates) => {
//setDates({ startDate,endDate });
console.log(dates);
}
,但在日期改变时,结果是这样的:{startDate: null,endDate: null}
我可以将默认日期更改为无效字符串,如下所示:
const [dates,setDates] = useState({ startDate: 'jkhjkhjk',endDate: null });
以及绑定更改事件 {startDate: "jkhjkhjk",endDate: null}
带有日期无效值的警告
解决方法
问题是文档不清楚 DayPickerRangeController
和所需的道具 focusedInput
:
它必须是 startDate
而不是 null
:
const [focusedInput,setFocusedInput] = useState('startDate');
或来自常量:
import { START_DATE,END_DATE } from 'react-dates/constants';
...
const [focusedInput,setFocusedInput] = useState(START_DATE);
并确保它不是 null
,就像在选择 endDate
之后一样:
focusedInput={focusedInput || START_DATE} // startDate
工作演示:
https://codesandbox.io/s/react-dates-date-range-picker-forked-e8qne?file=/src/date-picker.jsx