antd AutoComplete 自定义组件阻止事件向上冒泡

2,333 阅读1分钟

前言:

 遇到项目具体的问题,整了半天才解决,仅仅作为个人笔记学习,不喜勿喷。

1.问题描述

   在AutoComplete 中使用Input 组件,想回车的时候触发一些操作,想法是通过阻止事件冒泡不让Input 的事件往上传。

          <AutoComplete       
            dataSource={renderOption()}     
           className={styles['search-auto-input']}    
           getPopupContainer={tr => tr}         
           backfill         
           value={companyName}       
           onSelect={handleSelect}           
           onChange={val => handleSearchChange(val)}       
           optionLabelProp="value"          
           style={{ padding: '0px', margin: '0px' }} 
           dropdownMenuStyle={{ maxHeight: 'none', padding: '0px', margin: '0px' }} 
          >      
            <Input 
                maxLength={50} 
                id='xkb-home-search' 
                 className={styles['global-search']}
             />       
         </AutoComplete>

1.1 第一次尝试

   想通过Input的事件onPressEnter 阻止事件冒泡。发现这段代码确实生效了,但是同时AutoComplete的onChange 也在随后触发了,说明并不能阻止冒泡。后来看到说react中用

e.nativeEvent.stopImmediatePropagation();去阻止,试了下,一样不管用。    

  const handleEnter =(e:any) => { 
      console.log('e----',e.nativeEvent.stopImmediatePropagation)   
    const val = e.target.value;   
    e.stopPropagation();   
    e.nativeEvent.stopImmediatePropagation();  
    e.preventDefault();    console.log('点击回车了')   
   console.log('autoSource-----',autoSource) 
    return false;
   }

1.2 第二次尝试

   后来看到react有两种事件,一种是合成事件,另一种是原生的事件。想通过监听原生事件去阻止事件冒泡。又了解到input 的事件监听流的过程为:输入框发生的事件流程依次为focus、keydown、input、keyup、change与blur。

*在keydown时阻止事件冒泡,在change 之前,就不会往上冒泡了

这里用到了hooks,原理都是一样的。

  useEffect(() => {    
    const searchId = document.getElementById('xkb-home-search');
      searchId &&  searchId.addEventListener('keydown',
     (e) => {     
     if(e.keyCode === 13) {       
     // 执行一下跳转       
     // handleEnter(e)     
      e.stopPropagation();    
      console.log('回车')       
     return ;    
     }   
  },true)    
    return () => {  
     searchId && searchId.removeEventListener('keydown',() => {},false)    }  
},[])

1.3input的监听事件流未验证待学习