ant.design的input框同时绑定onBlur和onPressEnter事件且方法为同一个方法后的结果
前几天在做项目时碰到了这么一件事,就是在input上面同时绑定onBlur事件和onPressEnter,而且这两个事件还同时使用一个方法处理逻辑,导致一个方法在onPressEnter事件后执行两次,就弄得像丈二的和尚一样,代码是这样的
<Input
name="input"
type="text"
key={item.id}
id={`${item.id}`}
onPressEnter={this.onPressEnter(true);}
onBlur={e => {
this.onPressEnter(e, true);
}}
disabled={
data.id && Fetherlist.length > 0 && detail === undefined
? !boxInputValue.box_code
: !visibleIndex
}
style={{ height: 40 }}
/>
心理活动
只要执行onPressEnter事件onPressEnter()方法就会执行两次,起初还以为是冒泡或者是捕获机制的原因,一通乱改,之后发现怎么调整都会触发两次,既然解决不了触发两次的情况了,就把注意力放在方法上,想着怎么通过if判断给它避开要执行的代码段,结果也是不理想,虽然是避开了onPressEnter事件,但又影响了onBlur事件的执行果然两者不能同时实现,想偷懒都不能够,然后通过浏览官网和各位大神的分享才知道当onPressEnter事件触发时就必然会出发onBlur事件,我的两个事件还使用的同一个方法。
导致原因
当onPressEnter事件执行会默认触发失去焦点事件,这时候onBlur事件监听到input失去焦点了就会触发自己的方法,这时候两个事件用的是同一个放法,所以会触发两回,
解决方法
就是在onPressEnter事件中手动调用失焦事件,让onPressEnter事件不执行已绑定的onPressEnter()方法
代码是这样实现的
<Input
name="input"
type="text"
key={item.id}
id={`${item.id}`}
onPressEnter={e => {
e.target.blur(e, true);
}}
onBlur={e => {
this.onPressEnter(e, true);
}}
disabled={
data.id && Fetherlist.length > 0 && detail === undefined
? !boxInputValue.box_code
: !visibleIndex
}
style={{ height: 40 }}
/>
写的不好,望各位大佬不吝赐教