问题
I'm using the DatePicker component of materialui and I need to get the value of two DatePicker components in one function to make a range.
I created a handleChange function that already allows to retrieve the value of a DatePicker component but for 2 component I can not do it.
I would like to know the steps I need to take.
this is my code :
import React from 'react';
import moment from 'moment';
import 'moment/locale/fr'
import DatePicker from 'material-ui/DatePicker';
import areIntlLocalesSupported from 'intl-locales-supported';
let DateTimeFormat;
if (areIntlLocalesSupported(['fr'])) {
DateTimeFormat = global.Intl.DateTimeFormat;
} else {
const IntlPolyfill = require('intl');
DateTimeFormat = IntlPolyfill.DateTimeFormat;
require('intl/locale-data/jsonp/fr');
require('intl/locale-data/jsonp/fa-IR');
}
class SearchByDate extends React.Component {
handleSearchByDate = (evt, date) => {
console.log(date)
}
render() {
return (
<div>
<DatePicker
ref="dateChoiceOne"
name="dateChoiceOne"
hintText="Date début"
DateTimeFormat={DateTimeFormat}
okLabel="OK"
cancelLabel="Annuler"
locale="fr"
onChange={this.handleSearchByDate}/>
<DatePicker
ref="dateChoiceTwo"
name="dateChoiceTwo"
hintText="Date fin"
DateTimeFormat={DateTimeFormat}
okLabel="OK"
cancelLabel="Annuler"
locale="fr"
onChange={this.handleSearchByDate} />
</div>
)
}
}
export default SearchByDate;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
回答1:
As the date selection from the 1st DatePicker and the 2nd DatePicker happens at different times, you can't get the 2 dates as arguments into the function.
Instead, you should create 2 differents functions, one for each DatePicker. Theses functions will save the dates as startDate
and endDate
, and you can check for state updates in componentDidUpdate
; once you have both dates set, you can do whatever you wanted to.
class SearchByDate extends React.Component {
componentDidUpdate = () => {
if (this.state.startDate && this.state.endDate) {
// Both dates are set, do something with it
}
}
handleChangeStartDate = (evt, date) => {
this.setState({
startDate: date,
});
}
handleChangeEndDate = (evt, date) => {
this.setState({
endDate: date,
});
}
render() {
return (
<div>
<DatePicker
ref="dateChoiceOne"
name="dateChoiceOne"
hintText="Date début"
DateTimeFormat={DateTimeFormat}
okLabel="OK"
cancelLabel="Annuler"
locale="fr"
onChange={this.handleChangeStartDate}
/>
<DatePicker
ref="dateChoiceTwo"
name="dateChoiceTwo"
hintText="Date fin"
DateTimeFormat={DateTimeFormat}
okLabel="OK"
cancelLabel="Annuler"
locale="fr"
onChange={this.handleChangeEndDate}
/>
</div>
)
}
}
来源:https://stackoverflow.com/questions/46950659/get-value-of-2-composant-datepicker-in-onchange-reactjs