在 onChange (ReactJS) 中获取 2 个组合物日期选择器的值



我正在使用materialui的DatePicker组件,我需要在一个函数中获取两个DatePicker组件的值才能创建一个范围。

我创建了一个handleChange函数,该函数已经允许检索DatePicker组件的值,但对于2个组件,我无法做到这一点。

我想知道我需要采取的步骤。

这是我的代码:

import React from 'react';
import moment from 'moment';
import 'moment/locale/fr'
import DatePicker from 'material-ui/DatePicker';
import areIntlLocalesSupported from 'intl-locales-supported';
let DateTimeFormat;
if (areIntlLocalesSupported(['fr'])) {
  DateTimeFormat = global.Intl.DateTimeFormat;
} else {
    const IntlPolyfill = require('intl');
    DateTimeFormat = IntlPolyfill.DateTimeFormat;
    require('intl/locale-data/jsonp/fr');
    require('intl/locale-data/jsonp/fa-IR');
}
class SearchByDate extends React.Component {
  handleSearchByDate = (evt, date) => {
    console.log(date)
  }
  render() {
    return (
      <div>
        <DatePicker
            ref="dateChoiceOne"
            name="dateChoiceOne"
            hintText="Date début"
            DateTimeFormat={DateTimeFormat}
            okLabel="OK"
            cancelLabel="Annuler"
            locale="fr"
            onChange={this.handleSearchByDate}/>
        <DatePicker
            ref="dateChoiceTwo"
            name="dateChoiceTwo"
            hintText="Date fin"
            DateTimeFormat={DateTimeFormat}
            okLabel="OK"
            cancelLabel="Annuler"
            locale="fr"
            onChange={this.handleSearchByDate} />
      </div> 
    )
  }
}
export default SearchByDate;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

由于第一个日期选择器和第二个日期选择器的日期选择发生在不同的时间,因此您无法将 2 个日期作为参数放入函数中。

相反,您应该创建 2 个不同的函数,每个 DatePicker 一个。这些函数会将日期保存为startDateendDate,您可以在componentDidUpdate中检查状态更新;一旦你确定了两个日期,你可以做任何你想做的事情。

class SearchByDate extends React.Component {
  componentDidUpdate = () => {
    if (this.state.startDate && this.state.endDate) {
      // Both dates are set, do something with it
    }
  }
  handleChangeStartDate = (evt, date) => {
    this.setState({
      startDate: date,
    });
  }
  handleChangeEndDate = (evt, date) => {
    this.setState({
      endDate: date,
    });
  }
  render() {
    return (
      <div>
        <DatePicker
          ref="dateChoiceOne"
          name="dateChoiceOne"
          hintText="Date début"
          DateTimeFormat={DateTimeFormat}
          okLabel="OK"
          cancelLabel="Annuler"
          locale="fr"
          onChange={this.handleChangeStartDate}
        />
        <DatePicker
          ref="dateChoiceTwo"
          name="dateChoiceTwo"
          hintText="Date fin"
          DateTimeFormat={DateTimeFormat}
          okLabel="OK"
          cancelLabel="Annuler"
          locale="fr"
          onChange={this.handleChangeEndDate}
        />
      </div> 
    )
  }
}

最新更新