更改结束日期后如何触发方法

时间:2019-06-29 16:06:01

标签: javascript reactjs jsx react-dates

我正在使用Airbnb react-dates。我已将其添加到我的项目中,并且工作正常,该组件如下所示:

<DateRangePicker
    startDate={this.state.startDate} // momentPropTypes.momentObj or null,
    startDateId="your_unique_start_date_id" // PropTypes.string.isRequired,
    endDate={this.state.endDate} // momentPropTypes.momentObj or null,
    endDateId="your_unique_end_date_id" // PropTypes.string.isRequired,
    onDatesChange={this.onDatesChange} // PropTypes.func.isRequired,
    focusedInput={this.state.focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null,
    onFocusChange={focusedInput => this.setState({ focusedInput })} // PropTypes.func.isRequired,
    daySize={50}
    noBorder={true}
    isOutsideRange={() => false}
  />

我刚刚将其添加到我的项目中,并且您可以看到我的方法onDatesChange一切都很好,但是我想知道当选择END_DATE时如何触发某种方法。

例如,我想在触摸结束日期时进行过滤...

2 个答案:

答案 0 :(得分:2)

您需要在onDatesChange属性中添加回调:

<DateRangePicker
  {...dateRangePickerProps}
  onDatesChange={({ endDate }) => {
    console.log("End Date change callback"); // Your callback
  }}
/>;

答案 1 :(得分:2)

您需要使用onFocusChangeonDatesChange<DateRangePicker>道具,以及componentDidUpdate() React生命周期方法:

CodeSandbox

import React, { Component } from "react";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
import { DateRangePicker } from "react-dates";
import { START_DATE, END_DATE } from "react-dates/constants";

export default class Dates extends Component {
  state = {
    startDate: null,
    endDate: null,
    focusedInput: null
  };

  onDatesChange = ({ startDate, endDate }) =>
    this.setState({ startDate, endDate });

  onFocusChange = focusedInput => this.setState({ focusedInput });

  componentDidUpdate(prevProps, prevState) {
    if (
      prevState.focusedInput !== this.state.focusedInput &&
      this.state.focusedInput === END_DATE
    ) {
      alert("End date is focused!"); // your code here
    }

    if (prevState.endDate !== this.state.endDate) {
      alert("End date is changed!"); // your code here
    }
  }

  render() {
    const { startDate, endDate, focusedInput } = this.state;

    return (
      <DateRangePicker
        startDate={startDate}
        startDateId={START_DATE}
        endDate={endDate}
        endDateId={END_DATE}
        onDatesChange={this.onDatesChange}
        focusedInput={focusedInput}
        onFocusChange={this.onFocusChange}
      />
    );
  }
}