React js multiple instances of date picker

与世无争的帅哥 提交于 2020-03-16 08:34:08

问题


I am having problem updating the date on react-datepicker if I use multiple instances of datepicker.

Date picker Component:

<DatePicker
  selected={this.state.from}
  onChange={this.changeDate.bind(this)}
/>

On change handler:

changeDate(date) {
    this.setState({
        from : date
    });
}

This seems to work fine if i am using only one instance, but when I add more than one instances, I have to create separate onchange handler for each of the newly created date picker component. What I am looking for is a way to write just a single onchange handler function and handle change events for multiple instances of datepicker in that same function.


回答1:


You can have a object field state to store each date value in property

this.state = {
    fields: {}
}

handleDateChange = (dateName, dateValue) => {
    this.setState({
        fields: {
            ...this.fields,
            [dateName]: dateValue
        }
    })
}

// IN RENDER
<ReactDatepicker 
    value={this.fields["dateStart"]}
    onChange={(value) => handleDateChange("dateStart", value)}
/>



回答2:


You can have onChange Handler like that with two argument dateName and dateValue

//in state
 this.state = {
  startDate: moment(),
  endDate: moment(),
}

//My onChange handler function    
handleDateChange(dateName, dateValue) {
    let { startDate, endDate } = this.state;
    if (dateName === 'startDateTime') {
      startDate = dateValue;
    } else {
      endDate = dateValue;
    }
    this.setState({
      startDate,
      endDate,
    });
  }

// Date Picker component
<DatePicker
    id="start-date-time"
    name="startDateTime"
    className="form-control"
    selected={this.state.startDate}
    value={this.state.startDate}
    onChange={date => this.handleDateChange('startDateTime', date)}
    showTimeSelect
    timeFormat="HH:mm"
    timeIntervals={15}
    dateFormat="YYYY-MM-DD, h:mm a"
    timeCaption="time"
  />
//other use of Date picker
<DatePicker


 id="end-date-time"
  name="endDateTime"
  className="form-control"
  selected={this.state.endDate}
  value={this.state.endDate}
  onChange={date => this.handleDateChange('endDateTime', date)}
  placeholderText="choose end date of event"
  isClearable={true}
  showTimeSelect
  timeFormat="HH:mm"
  timeIntervals={15}
  dateFormat="YYYY-MM-DD, h:mm a"
  timeCaption="time"
/>


来源:https://stackoverflow.com/questions/50867479/react-js-multiple-instances-of-date-picker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!