在 React 中悬停时显示元素或文本:
onMouseOver
和 onMouseOut
属性。import {useState} from 'react';const App = () => {const [isHovering, setIsHovering] = useState(false);const handleMouseOver = () => {setIsHovering(true);};const handleMouseOut = () => {setIsHovering(false);};return (handleMouseOver}onMouseOut={handleMouseOut}>Hover over me {isHovering && (Only visible when hovering div
jiyik.com
)}
代码示例展示了如何在将鼠标悬停在另一个元素上时显示一个元素。
我们在 div 元素上设置了 onMouseOver
属性,因此每次用户将鼠标悬停在该元素上时,都会调用 handleMouseOver
函数。
handleMouseOver}onMouseOut={handleMouseOut}
>Hover over me
当用户将光标移动到元素或其子元素之一时,将触发 mouseover
事件。
在我们的
handleMouseOver
函数中,我们只需将isHovering
状态变量设置为 true。
const handleMouseOver = () => {setIsHovering(true);
};
相反,在我们的 handleMouseOut
函数中,我们将状态变量设置为 false。
const handleMouseOut = () => {setIsHovering(false);
};
当用户的光标不再包含在元素或其子元素之一中时,将触发 mouseout
事件。
我们使用逻辑与 &&
运算符有条件地呈现另一个 div 元素。
逻辑与 &&
运算符如果为假,则返回左侧的值,否则返回右侧的值。
如果状态变量存储假值,逻辑与
&&
运算符将返回假,并且不会呈现任何内容。
忽略布尔值、null 和 undefined。 他们根本不渲染。
当用户将鼠标悬停在 div 元素上时:
相反,当用户将光标移出 div 元素时:
将鼠标悬停在另一个元素上时,可以使用相同的方法来显示组件。
import {useState} from 'react';function Heading() {return (jiyik.com
);
}const App = () => {const [isHovering, setIsHovering] = useState(false);const handleMouseOver = () => {setIsHovering(true);};const handleMouseOut = () => {setIsHovering(false);};return (handleMouseOver}onMouseOut={handleMouseOut}>Hover over me {isHovering && }
当我们将鼠标悬停在 div
元素上时,代码示例会显示一个组件。
我们将一个 div
和一个 h2
提取到 Heading 组件中。
每次用户将鼠标悬停在设置了 onMouseOver
和 onMouseOut
属性的 div 上时,都会显示 Heading 组件。
当用户将鼠标移出 div 时,Heading 组件将卸载并且不再呈现。