简体   繁体   中英

React select onChange not called when options change

I have a <select> in my component where the list of options is filtered depending on state and is initialized with nothing.

render() {
  <select value={this.state.time} className='input' onChange={e => this.setState({time: e.target.value})} disabled={!this.state.date} >
    { availableDates.filter(d => moment(d).format('YYYY-MM-DD') === this.state.date).map(d =>
       <option key={d} value={moment(d).format('H:mm')}>{moment(d).format('H:mm')}</option>
    )}
</select>
}

It means that as long as this.state.date is null , the select has no option . Then when date is set, there is most of the time only one value. On the display, it becomes immediately selected.

But onChange is not triggered, and never is (even if I explicitly select the value).

Is this the expected behavior? Somehow, I'd say the value changed so the onChange should be triggered, shouldn't it?

Besides, how can I make it work anyway? I need the select to be displayed even without options ...

Yes, the state value was changed, but the select's change event, in fact, wasn't, it just got re-rendered with the new value.

Also, most browsers don't trigger the change event when re-selecting the current value (but if I recall it correctly, some old IEs do).

Hence, I believe that it's the expected behavior.

To make it work, in the code that sets the date state, it could also set the default time value. That makes sense, because you want to set the time when the date has changed.

As a side note, depending on how you'll implement that, you may want to take a look into uncontrolled components .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM