ReactJS-即使从选择下拉列表中选择了相同的选项,也会触发事件 [英] ReactJS - trigger event even if the same option is selected from select dropdown
问题描述
当从ReactJS的下拉列表中选择一个选项时,如何触发事件.目前,我正在使用 onChange
,但是即使再次选择相同的选项,我也需要触发一个事件.
How do I fire an event when an option is selected from dropdown in ReactJS. Currently I am using onChange
but I need to fire an event even if same option is selected again.
当前代码:
<select name="select1" onChange={this.onChangeOption}>
<option value='A'>Please select A...</option>
<option value='B'>Please select B...</option>
<option value='C'>Please select C...</option>
<option value='D'>Please select D...</option>
</select>
我什至尝试将 onClick
处理程序添加到选项中,但是由于仅适用于元素,因此在单击选项时不会触发.
I even tried adding onClick
handler to option but that does not fire on click over the options as it works only with elements.
我知道有使用jquery的解决方案,方法是将click事件与option元素绑定在一起,但是在React中需要一个解决方案.不想仅为此要求包括jQuery.
I know there are solutions using jquery by binding click event with option element, but need a solution in React. Dont want to include jQuery for only this requirement.
推荐答案
这是技巧,但如果您需要对所有更改都执行功能,即使更改了相同的选项,我也只知道一种解决方案-使用onClick和详细信息:
This is trick, but if you need to fire function with the all changes, even with change of the same option, only one solution I know - use onClick and its detail:
class Select extends React.Component{
onChangeOption(e){
if (e.detail === 0){
console.log(e.target.value);
}
}
render(){
return (
<select name="select1" onClick={this.onChangeOption}>
<option value='A'>Please select A...</option>
<option value='B'>Please select B...</option>
<option value='C'>Please select C...</option>
<option value='D'>Please select D...</option>
</select>
)
}
}
https://jsfiddle.net/69z2wepo/86140/
这篇关于ReactJS-即使从选择下拉列表中选择了相同的选项,也会触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!