airbnb/react-dates DayPickerRangeController 在某些函数调用中设置可见月份

airbnb/react-dates DayPickerRangeController set visible month on some function call

有没有办法设置 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;