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

时间:2019-09-28 01:01:46

标签: reactjs react-day-picker

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

1 个答案:

答案 0 :(得分:1)

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

不要用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用作ref

let toInput = React.createRef();


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

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

Demo