简体   繁体   English

选项更改时不调用反应选择onChange

[英]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. 我的组件中有一个<select> ,其中选项列表根据状态进行过滤,并且不进行任何初始化。

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 . 这意味着只要this.state.datenullselect就没有任何option Then when date is set, there is most of the time only one value. 然后,在设置date ,大多数时候只有一个值。 On the display, it becomes immediately selected. 在显示屏上,它将立即被选择。

But onChange is not triggered, and never is (even if I explicitly select the value). 但是onChange不会触发,也永远不会触发(即使我明确选择了该值)。

Is this the expected behavior? 这是预期的行为吗? Somehow, I'd say the value changed so the onChange should be triggered, shouldn't it? 不知何故,我会说值已更改,因此应该触发onChange ,不是吗?

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. 是的,状态值已更改,但是select的change事件实际上并没有,只是使用新值重新呈现了它。

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). 此外,大多数浏览器在重新选择当前值时不会触发change事件(但是,如果我正确地记得它,则某些旧的IE会触发)。

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 . 附带说明一下,根据实现方式的不同,您可能需要查看不受控制的组件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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