如何在 React 无状态组件中引用 'this' 关键字

How to refer 'this' keyword in React Stateless Component

我正在尝试使用库 day-picker 为输入范围日期选择器创建 React 无状态组件。

如果我尝试将有状态组件转换为无状态组件,则无法访问 this 关键字,因为无状态组件没有 this.

的作用域

我是 React 和 Hooks 的新手,尽了最大努力解决问题,但不知何故未能解决问题,这就是我正在尝试的。

问题 - 日期选择器范围输入未按预期工作。日历显示始终从当前月份开始。但不知何故,它是从去年开始的。

Actual Code

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;

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

不要用 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
});

另一件事是,class 中的 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 变量,而不是直接使用状态 ref

let toInput = React.createRef();


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

我已根据您提供的 actual code 问题对您的代码进行了一些修改。

Demo