使用 react-dateTime 组件的值设置状态

Setting state with the value of a react-dateTime component

我需要帮助。我正在使用一个 react-dateTime 组件,我只是想像表单中的每个其他字段一样获取该组件的值。但是我无法获取所选日期的值,更不用说将其与其他字段的其他属性一起存储在状态中了。

这是我的代码:

日期时间组件

  <Datetime
    onChange={this.handleChange}
    value={startDate}
    timeFormat={true}
    name="startDate"
    inputProps={{ placeholder: "Start Date" }}
   />

事件处理程序

  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

第二个 onchange 处理程序

 handleSelectDate = event => {
    if (event.target.name === "startDate") {
      this.setState({ startDate: event.target.value});
    } else {
      this.setState({ endDate: event.target.value });
    }
  }```

The state object

 this.state= { startDate: '' }

我尝试了不同的方法,目前我得到一个错误 event.target 未定义,所以根本没有事件,我还尝试通过在 onChange[=13= 上调用事件来初始化处理程序]

谢谢

它不像常规 input 那样通过 name

获取其值

onChange: Callback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string). Docs

试试这个:

class App extends React.Component {

  state = {
    startDate: ""
  }
  // You need to bind "this"
  handleChange = this.handleChange.bind(this)

  // Receives the selected "moment" object as only parameter
  handleChange(date) {
    this.setState({ startDate: date })
  }

  render() {
    return (
      <div>
        <Datetime
          value={this.state.startDate}
          onChange={this.handleChange}
          timeFormat={true}
          inputProps={{ placeholder: "Start Date" }}
        />
        <hr />
        Select date:{" "}
        {this.state.startDate ? this.state.startDate.toString() : "no selected date"}
      </div>
    )
  }
}

检查此 codeSandbox 示例。

虽然有效,但有点过时了,我鼓励您查看 react-datetime-picker or react-date-picker