首页 > 解决方案 > 如何在 React 中正确地从 datepicker 发送日期?

问题描述

我有两个组件。我需要获取日期并将其发送给获取。在组件MainPage 中,我为日期值添加了状态。在组件InputForm中,我添加了 react-data-picker。

当用户将日期设置为数据选择器时,此值应以“dd.mm.yyyy”或“yyyy-mm-dd”格式发送以获取(我使用dateFormat进行更改)。

结果我有这个MainPage代码:

import React, { PropTypes, Component } from 'react';
import dateFormat from 'dateformat';

class ReportPage extends Component {
  constructor(props) {
    super(props);
    this.state = {      
      date1: new Date(),
      date2: new Date()      
    };  
    this.onHandleFetch = this.onHandleFetch.bind(this);
    this.onChangeInputDate1 = this.onChangeInputDate1.bind(this);
    this.onChangeInputDate2 = this.onChangeInputDate2.bind(this);
    this.checkInputs = this.checkInputs.bind(this);    
  }

  handleShowClick() {         // if button clicked 
    if (this.checkInputs()) {     // if dates not null
      this.onHandleFetch(); 
    }
  }

  checkInputs() {
    if (this.state.date1 === null || this.state.date2 === null) {
      return false;
    }   
    return true;
  }

  onChangeInputDate1(d1) {   
    console.log(dateFormat(d1, 'isoDate')); // format yyyy-mm-dd
    this.setState({
      date1: d1     
    });
  }

  onChangeInputDate2(d2) {
    console.log(dateFormat(d2, 'isoDate'));
    this.setState({
      date2: d2
    });
  } 

  onHandleFetch() {    
    fetch(`${Config.baseUrl}/find/${dateFormat(this.state.date1, 'isoDate')}/
    ${dateFormat(this.state.date2, 'isoDate')}`, {
      method: 'GET'
    })
        ...
  }

  render() {
    return (
      <div>        
       <InputForm
         handleChangeInputDate1={this.onChangeInputDate1} handleChangeInputDate2={this.onChangeInputDate2}
         date1={this.state.date1} date2={this.state.date2}
       />
      )
    ...
    }

输入表格

import React, { PropTypes, Component } from 'react';
import DatePicker from 'react-date-picker';

const propTypes = {  
  date1: PropTypes.string,
  date2: PropTypes.string,
  handleChangeInputDate1: PropTypes.func,
  handleChangeInputDate2: PropTypes.func
};

class InputForm extends Component {
  constructor(props) {
    super(props);
    this.handleOnChange1 = this.handleOnChange1.bind(this);
    this.handleOnChange2 = this.handleOnChange2.bind(this);
  }

  handleOnChange1(date1) {
    this.props.handleChangeInputDate1(date1);
  }

  handleOnChange2(date2) {
    this.props.handleChangeInputDate2(date2);
  }

  render() {
    return (
      <form>
       ...
         <DatePicker onChange={this.handleOnChange1}
           value={this.props.date1}
         />               
         <DatePicker onChange={this.handleOnChange2}
           value={this.props.date2}
         />
       ...
      </form>
    );
  }
}

结果我在控制台中有这个错误:

对象作为 React 子对象无效(发现时间:2018 年 10 月 17 日星期三 00:00:00 GMT+0500 (Екатеринбург, стандартное время))。

我该如何解决?

标签: reactjsdatapicker

解决方案


推荐阅读