在日期选择器关闭时调用函数,当我仅在日期选择器外部单击时
Calling a function when the datepicker closes, when I click only outside of the datepicker
是否可以将日期选择器设置为仅在我点击日期选择器外部时关闭?关闭日历时,如果选择了日期,调用了alertDate
函数?
代码在这里:https://stackblitz.com/edit/react-o8dm7y
class App extends Component {
constructor() {
super();
this.state = {
selectedDate: '',
arrayDates: []
};
}
handleChangeDate = (date) => {
let newArrayDates = [...this.state.arrayDates]
newArrayDates.push(date)
this.setState({
selectedDate: date,
arrayDates: newArrayDates
})
}
alertDate = () => {
console.log(this.state.selectedDate)
}
render() {
console.log(this.state.arrayDates)
return (
<div>
<DatePicker
selected={this.state.selectedDate}
onChange={this.handleChangeDate}
showTimeSelect
timeFormat="HH:mm"
timeIntervals={15}
dateFormat="MMMM d, yyyy h:mm aa"
timeCaption="time"
placeholderText="Choose date..."
/>
</div>
);
}
}
这是您的问题的解决方案:
- 您可以将
shouldCloseOnSelect
设置为 false
以仅在单击外部时关闭日期选择器。
- 对于调用
alertDate
你可以把它放在 onBlur
回调中。
以下是适合您的示例:
class App extends React.Component {
state = {
startDate: new Date()
};
handleChange = date => {
this.setState({
startDate: date
});
};
handleOnBlur = event => {
const date = new Date(event.target.value);
console.log(date);
};
render() {
return (
<DatePicker
key="example9"
selected={this.state.startDate}
onChange={this.handleChange}
shouldCloseOnSelect={false}
onBlur={this.handleOnBlur}
placeholderText="View blur callbacks in console"
/>
);
}
}
希望对您有所帮助!
是否可以将日期选择器设置为仅在我点击日期选择器外部时关闭?关闭日历时,如果选择了日期,调用了alertDate
函数?
代码在这里:https://stackblitz.com/edit/react-o8dm7y
class App extends Component {
constructor() {
super();
this.state = {
selectedDate: '',
arrayDates: []
};
}
handleChangeDate = (date) => {
let newArrayDates = [...this.state.arrayDates]
newArrayDates.push(date)
this.setState({
selectedDate: date,
arrayDates: newArrayDates
})
}
alertDate = () => {
console.log(this.state.selectedDate)
}
render() {
console.log(this.state.arrayDates)
return (
<div>
<DatePicker
selected={this.state.selectedDate}
onChange={this.handleChangeDate}
showTimeSelect
timeFormat="HH:mm"
timeIntervals={15}
dateFormat="MMMM d, yyyy h:mm aa"
timeCaption="time"
placeholderText="Choose date..."
/>
</div>
);
}
}
这是您的问题的解决方案:
- 您可以将
shouldCloseOnSelect
设置为false
以仅在单击外部时关闭日期选择器。 - 对于调用
alertDate
你可以把它放在onBlur
回调中。
以下是适合您的示例:
class App extends React.Component {
state = {
startDate: new Date()
};
handleChange = date => {
this.setState({
startDate: date
});
};
handleOnBlur = event => {
const date = new Date(event.target.value);
console.log(date);
};
render() {
return (
<DatePicker
key="example9"
selected={this.state.startDate}
onChange={this.handleChange}
shouldCloseOnSelect={false}
onBlur={this.handleOnBlur}
placeholderText="View blur callbacks in console"
/>
);
}
}
希望对您有所帮助!