2

我正在尝试使用库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;
4

1 回答 1

2

在将基于类的组件转换为功能组件时,有很多事情需要弄清楚/考虑。

不要用new Date(),初始化你的状态

const [days, setDays] = useState({
  from: new Date(),
  to: new Date(today.getTime() + 24 * 60 * 60 * 1000)
});

你的日期格式new Date()和你的日期格式DayPickerInput不一样。因此,您需要将其保留为undefined/ 转换为您理解的new Date()格式。DayPickerInput

const [days, setDays] = useState({
  from: undefined,
  to: undefined
});

另一件事是,setState基于类的组件和功能组件的工作方式略有不同。setState在功能组件中没有回调。

这个setState有点不对

const handleFromChange = from => {
  // Change the from date and focus the "to" input field
  setDays({ from, to }, showFromMonth);
};

const handleToChange = to => {
  setDays({ from, to });
};

这里showFromMonth回调不起作用。您需要一个单独的useEffect钩子来监听状态变化并相应地运行副作用/回调,

const handleFromChange = from => {
  // Change the from date and focus the "to" input field
  //This is functional setState which will only update `from` value
  setDays(days => ({
     ...days,
     from
  }));
};

const handleToChange = to => {
  //This is functional setState which will only update `to` value
  setDays(days => ({
    ...days,
    to
  }));
};

//This is useEffect hook which will run only when `to` value changes
useEffect(()=>{
  showFromMonth();
},[days.to, showFromMonth])

您已提供ref给您的第二个日期选择器,

ref={el => {
    days.to = el;
}}

您应该单独创建一个ref变量,而不是直接使用 state as ref

let toInput = React.createRef();


ref={el => {
   toInput = el;
}}

我根据您提供的实际代码对您的代码进行了一些修改。

演示

于 2019-09-28T04:16:24.550 回答