简体   繁体   中英

Unable to set default value in date range picker-ant js react

I am using a date range picker from ant js. https://ant.design/components/date-picker/

I can get the start and end date from the date picker and set it in the states . But if i want to set the defaut value to date picker, I unable to set it. It shows below error:

react-dom.production.min.js?ca5d:196 Error: The value/defaultValue of RangePicker must be a moment object array after `antd@2.0`, 

Here's the Code:

import React from 'react';
import { DatePicker} from 'antd';

class DataCheck extends React.Component {
    state = { startDate:"",endDate:""}

    onDateChange(date) {
        this.setState({startDate:date[0]['_d'],endDate: date[1]['_d']})
    }
    onInitialDateSet(){
        var end_date = new Date();
        end_date.setDate(end_date.getDate()-15)
        this.setState({startDate:new Date(), endDate:end_date})
    }
    componentDidMount(){
        this.onInitialDateSet()
    }
    render() {
        const { RangePicker } = DatePicker;
        return (
            <div>
                <RangePicker defaultValue ={[moment(this.state.startDate), moment(this.state.endDate)]} size={'small'} onChange={this.onDateChange.bind(this)} /> 
            </div>
        );
    }
}
export default DateCheck

Help me with some solutions.

I faced similar issue. In my case I received dates in array of strings and had to pre-populate in RangePicker. Later I found out that, it just needs typeof moment.Moment object and nothing else. So I created a function like this:

private formatStringsToDate = (dates: Array<string>) => dates.map((date: string) => moment(date));

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