在日期选择器关闭时调用函数,当我只在日期选择器之外单击时

IT技术 javascript reactjs react-datepicker
2021-05-15 17:42:34

是否可以将日期选择器设置为仅在我在日期选择器外部单击时关闭?关闭日历时,如果选择了日期,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>
    );
  }
}
1个回答

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

  1. 您可以设置shouldCloseOnSelectfalse仅在单击外部时关闭日期选择器。
  2. 对于呼叫,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"
      />
    );
  }
}

希望这可以帮助!