airbnb/react dates DayPickerRangeController在某个函数调用上设置了可见月份



有没有办法在组件渲染后的一个月内设置DayPickerRangeController自定义可见?我有"handleMonthChange"函数,我想在调用该函数时更改可见月份。我试图设置"initialVisible"月份,但它不起作用。

import { useState } from "react";
import moment from "moment";
import { DayPickerRangeController } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
const Date = (props) => {
const [startDate, setStartDate] = useState(null);
const [endDate, setEndDate] = useState(null);
const [focusedInput, setFocusedInput] = useState("startDate");
const [initialMonth, setInitialMonth] = useState(moment("01-01-2021"));
const handleDatesChange = ({ startDate, endDate }) => {
setStartDate(moment(startDate, "MMM DD, YYYY"));
setEndDate(moment(endDate, "MMM DD, YYYY"));
};
const handleMonthChange = () => {
console.log("month change");
setInitialMonth(moment("01-06-2021"));
};
return (
<div>
<DayPickerRangeController
onDatesChange={handleDatesChange}
focusedInput={focusedInput}
startDate={startDate}
endDate={endDate}
numberOfMonths={2}
initialVisibleMonth={() => initialMonth}
/>
<button onClick={handleMonthChange}>Change Visible Month</button>
</div>
);
};
export default Date;

我找到了解决方法。卸载组件,然后使用新的initialMonth 进行渲染

import { useState } from "react";
import moment from "moment";
import { DayPickerRangeController } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
const Date = (props) => {
const [startDate, setStartDate] = useState(null);
const [endDate, setEndDate] = useState(null);
const [focusedInput, setFocusedInput] = useState("startDate");
const [initialMonth, setInitialMonth] = useState(moment("01-01-2021"));
const handleDatesChange = ({ startDate, endDate }) => {
setStartDate(moment(startDate, "MMM DD, YYYY"));
setEndDate(moment(endDate, "MMM DD, YYYY"));
};
const handleMonthChange = () => {
setInitialMonth(null)
setTimeout(() => setInitialMonth(moment("01-06-2021")), 0);
};
if(!initialMonth) return <div>Loading...</div>
return (
<div>
<DayPickerRangeController
onDatesChange={handleDatesChange}
focusedInput={focusedInput}
startDate={startDate}
endDate={endDate}
numberOfMonths={2}
initialVisibleMonth={() => initialMonth}
/>
<button onClick={handleMonthChange}>Change Visible Month</button>
</div>
);
};
export default Date;

相关内容

  • 没有找到相关文章

最新更新