如何使用 react-datetime 获取选定的日期?

How to get selected date using react-datetime?

我正在使用开箱即用的 react-datetime

现在,我正在尝试将选定的日期保存到我的 date 状态中。

import DateTime from 'react-datetime';
import '../DateTime.css';

class SomeClass extends React.Component {
  render(){
    return (
      <div>
        <DateTime onChange={this.props.handleDate}/>
      ...

上面的程序有效 - 它会显示一个简单的框,当有人单击它时会显示日历。

这里是handleDate方法:

  ...
  handleDate(e){
    this.setState({date: e.target.value}, () => console.log(this.state.date))
  };

它适用于我的常规 ol'react-bootstrap 组件:<FormControl type="date" onChange={this.props.handleDate} /> 但是当我使用 DateTime 时,它说它的值未定义。 “Schedule.js:135 Uncaught TypeError: Cannot read property 'value' of undefined

我正在查看 npm site 中的 API,但没有看到任何显示如何获取数据的示例。我可能读多了。

如何使用 DateTime 获取所选日期的值? e.target.value 似乎不适用于这种情况。

来自文档: 日期改变时触发回调。如果输入中的日期有效,则回调接收所选时刻对象作为唯一参数。如果输入中的日期无效,回调将接收输入的值(字符串)。

使用此信息,处理程序应如下所示:

handleDate(date){
   this.setState({date}); # ES6 
};

添加到 Oluwafemi Sule 的回答中,要从时刻对象获取日期对象,您需要使用 .toDate() 而不是根据时刻使用任何内部属性,例如 _d。

Moment uses a technique called epoch shifting that causes this property to sometimes differ from the actual date value that the Moment reflects. In particular if Moment TimeZone is in use, this property will almost never be the same as the actual value that Moment will output from its public .format() function. As such, the values of _d and any other properties prefixed with _ should not be used for any purpose.

To print out the value of a Moment, use .format(), .toString() or .toISOString().

To retrieve a native Date object from Moment, use .toDate(). This function returns a properly shifted date for interaction with third party APIs.

Moment.js Guide

来晚了,但它会帮助某人。

import Datetime from 'react-datetime';

 class User extends React.Component {

    constructor(props) {
        super(props);
        this.state = {  
              date: "",
              time: "",
        }
     }
changeDate = (event) => {
     console.log(event.toDate()) // Tue Nov 24 2020 00:00:00 GMT+0400 (Gulf Standard Time)
     console.log(event.format("DD-MM-YYYY")) //24-11-2020
     this.setState({...this.state, date: event.format("DD-MM-YYYY")}) 
}

changeTime = (event) => {
    console.log(event.format("HH-mm-ss a")) //02-00-00 am
    this.setState({...this.state, time: event.format("HH-mm-ss a")})
}

  render() {
    return (
            <div>
              <Datetime
                     id="datepicker"
                           viewMode="days"
                           timeFormat={false}
                            dateFormat="DD-MM-YY"
                            value={this.state.date}
                           onChange={this.changeDate}

                    />


                <Datetime
                     id="timepicker"
                     viewMode="time"
                     dateFormat={false}
                     onChange={this.changeTime}
                     />
            </div>

     )
  }


}