检查鼠标是否在特定的react组件上



我正试图停止一些基于条件的行为,如果鼠标悬停在一个特定的反应组件在我的应用程序。

我只能找到旧的答案引用jQuery和JS香草。还有别的办法吗?还是不能接受?

下面是我感兴趣的组件,用于确定鼠标是否在上方:

<ContentRightHandSide offset={bannerHidden ? 80 : 120}>
<ContentTitle>
Activity
<img
style={{
display: "inline",
position: "relative",
marginLeft: "20px",
width: "35px",
}}
src={calendarIcon}
/>
</ContentTitle>
{authStatus === "authenticated" ? (
<ShareLogs
linkShareLogs={activeShareLogs}
isBannerHidden={bannerHidden}
hovered={hoveredNode}
selected={selectedNode}
/>
) : (
<div style={{ position: "relative" }}>
<img
src={blurredScreenLinks}
style={{
fontSize: "24px",
position: "relative",
margin: "0 auto",
width: "100%",
}}
/>
<button
style={{
backgroundColor: "#F7F1FF",
color: "#35373B",
position: "absolute",
fontFamily: "lato",
left: "0",
right: "0",
marginLeft: "auto",
marginRight: "auto",
width: "320px",
top: "100px",
padding: "0px 20px",
display: "flex",
alignItems: "center",
borderRadius: "60px",
}}
onClick={handleSignInClick}
>
<img
style={{
display: "inline",
position: "relative",
width: "80px",
cursor: "pointer",
margin: "-5px",
}}
src={slackIcon}
/>
<span style={{ textAlign: "left" }}>
Lorem Ipsum                  
</span>
</button>
</div>
)}
</ContentRightHandSide>

你可以在React中像这样定义悬停事件,类似于你处理onClick的方式。

<Component
onMouseEnter={handleSomething}
onMouseLeave={handleSomething}
/>

有几种方法可以确定鼠标当前是否在React组件上,但是如何"停止某些行为"呢?这取决于你的行为如何运行。

如果你可以让你的行为依赖于一些状态变量,你可以给React组件一个处理程序来设置onmouseenteronmouseleave事件的状态:

const [isMouseOver, setIsMouseOver] = useState(false)
...
<ContentRightHandSide
onMouseEnter={() => setIsMouseOver(true)}
onMouseLeave={() => setIsMouseOver(false)}
offset={bannerHidden ? 80 : 120}
>
...
</ContentRightHandSide>

你给组件的处理程序也不需要设置状态变量,它可以执行任何需要的逻辑来改变你的行为。

这个JSFiddle演示了基于类的组件中的行为。

您可能感兴趣的事件:https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event

官方的React文档中有一个关于处理事件的章节,可能会给你更多的想法。

最新更新