【问题标题】:how to auto trigger onChange function with selected value如何使用选定的值自动触发 onChange 函数
【发布时间】:2021-10-03 10:17:41
【问题描述】:

我有一个下拉菜单,我想在选择某些内容时触发一个功能。

<DatePicker
  customInput={
    <React.Fragment>
      <input
        tabIndex={this.props.tabIndex}
        className="exact-date-input"
        placeholder={this.props.placeholder}
        autoComplete="off"
        type="text"
        maxLength={10}
        id="date-input"
        aria-label={ariaLabel}
        value={this.state.inputValue}
        onKeyDown={this.onKeyDownDateType}
        onClick={()=>this.openOrCloseDatePicker(true, this.state.error)}
        onFocus={()=>this.openOrCloseDatePicker(true, this.state.error)}
        onBlur={()=>this.emptyIfError(this.state.error)}
      />
    </React.Fragment>
  }
  openToDate={this.openToDate(this.props.value)}
  tabIndex={-1}
  selected={this.openToDate(this.props.value)}
  customInputRef="dateInput"
  autoComplete="off"
  id={this.props.id}
  onChange={this.handleInput}
  required={this.props.required}
  minDate={moment(today).toDate()}
  maxDate={moment(endRange).toDate()}
  open={this.state.datePickerIsOpen}
  onClickOutside={()=>this.openOrCloseDatePicker(false, this.state.error)}
/>

这是我的 onChange 函数

  handleInput(e:any) {
    let value = moment(e).format('MM/DD/YYYY');

    this.props.onChange({
      target: {
        name: this.props.name,
        value: value
      }
    });

    this.setState({
      inputValue: value,
      datePickerIsOpen: false
    })

  }

我遇到的问题是,如果我选择已选择的选项,则不会触发该功能。我明白这是因为没有任何改变,但有没有办法解决这个问题?

【问题讨论】:

  • 有人知道如何解决这个问题吗?

标签: reactjs typescript react-typescript


【解决方案1】:

我明白这是因为没有任何改变。

显然onChange 仅在发生变化时才会被调用。

修复

查看您正在使用的DatePicker 的API,看看它是否有类似onSelectonOpen 之类的道具并使用它??

【讨论】:

  • 所以我只需要在 DatePicker 中添加onSelect={this.handleInput} 吗?我正在使用 react-datepicker
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-27
相关资源
最近更新 更多