customInput 未在 react-datepicker 中返回所选日期

customInput not returning the selected date in react-datepicker

我正在尝试打开 on the click of an icon. For that, I am using customInput parameter. The 正在单击图标打开,但 onChange 处理程序未获取选定的日期。这是我的代码:

<div className="date-icon">
    <DatePicker
        id="date-picker"
        dateFormat="YYYY-MM-DD"
        selected={this.state.startDate}
        showMonthDropdown
        onChange={this.handleDateChange.bind(this)}
        customInput={<img src="/img/cal.svg" alt=""/>}
        //includeDates={this.state.activityDates}
    />
    <br/>
 </div>

这里是 handleDateChange 函数

handleDateChange(date, event){
    console.log(document.getElementById("date-picker").value)
}

我在控制台日志中收到 undefined

当我删除 customInput 参数时,日期会按预期打印在控制台中。

默认输入是一个 input 元素,它有一个 value。您的自定义输入 <img src="/img/cal.svg" alt=""/> 不是输入元素,并且没有 value.

您可以将给定的时刻存储在 onChange 处理程序中,并将其存储在状态中并改为使用它。

例子

class App extends React.Component {
  state = { selectedDate: moment() };

  handleDateChange = m => {
    this.setState({ selectedDate: m });
    console.log(m.format("YYYY-MM-DD"));
  };

  render() {
    return (
      <DatePicker
        id="date-picker"
        dateFormat="YYYY-MM-DD"
        selected={this.state.selectedDate}
        showMonthDropdown
        onChange={this.handleDateChange}
        customInput={<img src="/img/cal.svg" alt=""/>}
      />
    );
  }
}