简体   繁体   中英

react-datepicker fails with moment and new Date

I am trying to set minDate property in react-datepicker component with moment :

if(this.props.minDate){
      console.log('date:' + moment(this.props.minDate)); //1517436000000

      return <DatePicker

       minDate={ new moment(this.props.minDate)} 
         selected={this.state.startDate}
         onChange={this.handleChange}
         disabled = {this.props.disabled}
     />

or with new Date :

console.log('new date:' + new Date(this.props.minDate)); // Thu Feb 01 2018 02:00:00 GMT+0200
return <DatePicker

       minDate={ new Date(this.props.minDate)} 
         selected={this.state.startDate}
         onChange={this.handleChange}
         disabled = {this.props.disabled}
     />

My minDate String - "2011-10-01" . And still the result is the current day and the are no errors in the console, thanks for any help.

I think You have to give value for this, because minDate and maxDate are for validation purpose. minDate will only be the resulting value only if, when given value or current date is less then min Date

class Example extends React.Component {
  constructor (props) {
    super(props)
    this.minDate = new moment(props.minDate)
    this.state = {
      startDate: props.minDate
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(date) {
    this.setState({
      startDate: date
    });
  }

  render() {
    return <DatePicker
     selected={this.state.startDate}
     onChange={this.handleChange}
     minDate={this.minDate}
     value={this.props.startDate}
   />;
  }
}

It seems to me that you do not need new instance of moment when you pass data to minDate prop. You are doing it like this minDate={ new moment(this.props.minDate)} .

React-datepicker already internally uses moment for manipulating data objects so I think you should just remove keyword new in front of a moment when you are passing it to the minDate prop.

我自己一个人,看来如果设置了selected属性,它将显示而不是minDate属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM