Calling a function when the datepicker closes, when I click only outside of the datepicker

妖精的绣舞 提交于 2020-04-16 04:24:29

问题


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?

Code here: 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>
    );
  }
}

回答1:


Here is the solution to your issues:

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

Hope this helps!



来源:https://stackoverflow.com/questions/57616929/calling-a-function-when-the-datepicker-closes-when-i-click-only-outside-of-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!