同时触发鼠标进入和离开事件
P粉018548441
P粉018548441 2023-08-13 18:26:33
[React讨论组]
<p><br /></p> <pre class="brush:php;toolbar:false;">&lt;Drawer anchor="left" className="drawerArea left-navigate" variant="permanent" open={true} PaperProps={{ style: { width: "inherit", background: "#172B4D", backgroundImage: `linear-gradient(to right,#172B4D 60% , white 40%)`, border: "none", overflowY: "hidden", }, }} &gt; &lt;Box&gt; &lt;Box&gt; &lt;Box&gt; &lt;Box className="listing" sx={{ width: "100%" }}&gt; &lt;List className="mp-0 wh-100 overflow-overlay"&gt; {menus &amp;&amp; menus.length &gt; 0 &amp;&amp; menus.map((item, index) =&gt; ( &lt;Box key={index}&gt; &lt;ListItem ref={popoverAnchor} className={`mp-0 navigationList flex-start-center`} ** onMouseEnter={(e) =&gt; { setNestedArr([...item?.children]); popoverEnter(e); setAnchorEl(e?.currentTarget); }} onMouseLeave={(e) =&gt; { popoverLeave(e); }}** onClick={(e) =&gt; { console.log(item,'parent_clicked') }} &gt; &lt;ListItemText&gt; &lt;Box&gt; {micons[item?.name] ? ( micons[item?.name] ) : ( &lt;Icon&gt;{item?.icon_class}&lt;/Icon&gt; )} &lt;/Box&gt; &lt;Typography&gt; {item?.name} &lt;/Typography&gt; &lt;/Typography&gt; } /&gt; &lt;/ListItem&gt; &lt;/Box&gt; ))} &lt;/List&gt; &lt;/Box&gt; &lt;/Box&gt; &lt;/Box&gt; {open &amp;&amp; nestedArr.length ? ( &lt;NestedMenu open={open} setOpen={(val) =&gt; setOpen(val)} anchorEl={anchorEl} nestedArr={nestedArr} lightBackground={lightBackground} secondaryColor={secondaryColor} popoverAnchor={popoverAnchor} popoverEnter={popoverEnter} popoverLeave={popoverLeave} /&gt; ) : null} &lt;/Box&gt; &lt;/Drawer&gt;</pre> <p><strong>页面左侧有一些菜单(使用MUI库和material-ui-nested-menu-item库),当鼠标悬停在Listitems上时,它会显示一个带有嵌套或子菜单的菜单,并在鼠标离开时关闭菜单,但我面临的问题是在悬停在菜单上时同时触发了onMouseLeave事件,所以菜单不会打开。我无法找出问题所在。</strong></p>
P粉018548441
P粉018548441

全部回复(1)
P粉366946380

在React中处理嵌套元素和鼠标事件时,您描述的问题是常见的。当您有嵌套元素并将onMouseEnter和onMouseLeave事件附加到父元素时,即使鼠标仍在父元素的范围内,移动鼠标到子元素上也会触发父元素的onMouseLeave事件。这是因为鼠标已经“离开”了父元素并“进入”了子元素。

为了解决这个问题,您可以使用onMouseOver和onMouseOut事件来替代onMouseEnter和onMouseLeave。onMouseOver和onMouseOut事件不会以相同的方式冒泡,因此它们可以帮助避免这个问题。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号