反应:更改鼠标上的图标输入使用状态。图标卡在"hover"状态,如果我移动鼠标太快



我有一个带有未选中复选框图标的组件。将鼠标悬停在图标上时,我显示的是该图标的已检查版本。我使用state在鼠标进入包含图标的div时将isHovered状态设置为true,在鼠标离开div时将其设置为false。我在div中进行条件渲染,如果isHoverd状态为false,则使用未选中的图标,如果isHovered为true,则使用选中的图标。

我的组件在我的应用程序中连续使用了多次,我的问题是,如果我在图标上快速移动鼠标,即使鼠标不再在图标上,其中一些图标也会被困在isHovered状态true。

有什么建议可以纠正这种行为吗?

这是我的代码:

const [isHovered, setIsHovered] = useState(false);
const onMouseEnter = () => {
setIsHovered(true);
};
const onMouseLeave = () => {
setIsHovered(false);
};
return (
<div
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
onClick={handleArchive}
style={{ display: "flex", alignItems: "center", cursor: "pointer" }}
>
{isHovered ? (
<CheckCircleIcon
style={{ color: "grey", fontSize: 20, marginRight: 10 }}
/>
) : (
<RadioButtonUncheckedIcon
style={{ color: "grey", fontSize: 20, marginRight: 10 }}
/>
)}
</div>

解决方案1:

const [isHovered, setIsHovered] = useState(false);

return (
<div
onMouseEnter={() => setIsHovered(!isHovered)}
onMouseLeave={() => setIsHovered(!isHovered)}
onClick={handleArchive}
style={{ display: "flex", alignItems: "center", cursor: "pointer" }}
>
{isHovered ? (
<CheckCircleIcon
style={{ color: "grey", fontSize: 20, marginRight: 10 }}
/>
) : (
<RadioButtonUncheckedIcon
style={{ color: "grey", fontSize: 20, marginRight: 10 }}
/>
)}
</div>

解决方案2:一个简单的纯css解决方案

最新更新