[英]React/JS - onMouseOver Changing the Text
所以我试图在使用 onMouseHover 时显示额外的文本,但我似乎无法理解它,就像我试图找出一种不必使用 CSS 或 JQuery 的方法。 如何根据函数调用使 onMouseHover 显示文本?
function URL() {
return (
<a href={url} onMouseOver={mouseOver()}>{mouseOver()}</a>
);
}
function mouseOver() {
return (
<p>Hovering</p>
);
}
class HoverableComponent extends React.Component {
constructor() {
super();
this.state = { text : '' }
}
//set the text
onMouseover (e) {
this.setState({text : 'some text'})
}
//clear the text
onMouseout (e) {
this.setState({text : ''})
}
render () {
const {text} = this.state;
return (
<div
onMouseEnter={this.onMouseover.bind(this)}
onMouseLeave={this.onMouseout.bind(this)}>{text}</div>
)
}
}
您可以结合使用 onMouseEnter 和 onMouseLeave 来更改状态(您需要在构造函数中对其进行初始化)。 例如:
function URL() {
return (
<a href={url} onMouseEnter={showText()} onMouseLeave={hideText()}>{this.state.text}</a>
);
}
function showText() {
this.setState({text : "Hovering"})
}
function hideText() {
this.setState({text : ""})
}
这是一个useHover
反应钩子。
如果您需要跟踪多个 dom 元素的悬停状态,它应该使它更清晰。
import { useState } from 'react'
function useHover() {
const [hovering, setHovering] = useState(false)
const onHoverProps = {
onMouseEnter: () => setHovering(true),
onMouseLeave: () => setHovering(false),
}
return [hovering, onHoverProps]
}
function myComponent() {
const [buttonAIsHovering, buttonAHoverProps] = useHover()
const [buttonBIsHovering, buttonBHoverProps] = useHover()
return (
<div>
<button {...buttonAHoverProps}>
{buttonAIsHovering ? "button A hovering" : "try hovering here"}
</button>
<button {...buttonBHoverProps}>
{buttonBIsHovering ? "button B hovering" : "try hovering here"}
</button>
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.