react-dates onDatesChange startDate 和 endDate 为空,DayPickerRangeController

问题描述

这是来自 DayPickerRangeControllerreact-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

enter image description here

它必须是 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