所以我在使用onMouseHover时尝试显示其他文本,但我似乎无法理解它,就像我试图找出一种方法而不必使用CSS或JQuery。如何根据函数调用使onMouseHover显示文本?
function URL() {
return (
<a href={url} onMouseOver={mouseOver()}>{mouseOver()}</a>
);
}
function mouseOver() {
return (
<p>Hovering</p>
);
}
答案 0 :(得分:7)
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>
)
}
}
答案 1 :(得分:0)
您可以使用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 : ""})
}
答案 2 :(得分:0)
这是一个 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>
)
}