问题
I have a multi-step form with child form components. On one of the components, I'm trying to implement YouCanBookMe DatePicker.
Now, when I try to update the state of datepicker's value like I do with other regular text inputs, the state does not get updated. If I typed the date, the state gets updated, but not when I actually select the date from the picker. I'm really clueless why. Can any of you point out why it doesn't?
Your help is greatly appreciated. I'm new to React and I've tried 3 different Datepicker libraries and I'm slowly going insane, because none seems to work or I'm not able to transform it to a Parent-Child structure. Thanks!
Parent:
constructor(props) {
super(props);
this.state = {
wants_interview_date: moment().format("DD-MM-YYYY")
}
}
handleChange(field) {
return (evt) => this.setState({ [field]: evt.target.value });
}
render(){
return <FormStep8
wants_interview_date={this.state.wants_interview_date}
onDateChange={this.handleChange('wants_interview_date')} />;
}
Child Component:
render() {
<Datetime
timeFormat={false}
dateFormat="DD-MM-YYYY"
inputProps={{id: 'wants_interview_date', onBlur: this.props.onDateChange, value: this.props.wants_interview_date}} //To get the regular HTML input props
/>
}
回答1:
The good friends at Reactiflux helped me solve the issue. Apparently Moment.js
was returning an Object on handleChange
and therefore the state was not showing anything. The output needed to use the _d Moment.js
method. Here is the correct handleChange
method:
handleDateChange(field) {
return evt => {
const value = evt._d;
this.setState({ wants_interview_date: value });
};
}
回答2:
this code snippet works fine for me, import DateTime (capital T)
import DateTime from 'react-datetime';
<DateTime name="newapp_time"
onChange={(e) => { this.setState({ newapp_time: moment(e).toJSON() }) }} />
the result is a timestamp in this case
来源:https://stackoverflow.com/questions/45456557/react-datepicker-input-state-not-changing