当日期选择器关闭时(仅在日期选择器外部单击时)调用函数 [英] Calling a function when the datepicker closes, when I click only outside of the datepicker

查看:103
本文介绍了当日期选择器关闭时(仅在日期选择器外部单击时)调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将日期选择器设置为仅在我在日期选择器外部单击时关闭?关闭日历时,如果选择了日期,是否调用了alertDate函数?

Is it possible to set the datepicker to close only when I click outside the datepicker? When closing the calendar, if the date was selected, the alertDate function was called?

此处的代码: 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>
    );
  }
}

推荐答案

以下是您解决问题的方法:

Here is the solution to your issues:

  1. 您可以将shouldCloseOnSelect设置为false以仅在外部单击时关闭日期选择器.
  2. 要调用alertDate,可以将其放入onBlur回调中.
  1. You can set shouldCloseOnSelect to false to close date picker only when its click outside.
  2. For calling alertDate you can put it in onBlur callback.

以下是适用于您的示例示例:

Here is the sample example which would work for you:

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"
      />
    );
  }
}

希望这会有所帮助!

这篇关于当日期选择器关闭时(仅在日期选择器外部单击时)调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆