我创建了几个带有特定内容标题的部分。
我想在悬停在不同部分上方时显示一个简短的预览。
有谁知道如何创建带有条件渲染react组件的 hoverActionHandler ?
我创建了几个带有特定内容标题的部分。
我想在悬停在不同部分上方时显示一个简短的预览。
有谁知道如何创建带有条件渲染react组件的 hoverActionHandler ?
您可以使用onMouseOver
和onMouseOut
来更改状态并根据状态值有条件地渲染组件。
看看它在行动:
挂钩:
import React, { useState } from "react";
import { render } from "react-dom";
const HoverableDiv = ({ handleMouseOver, handleMouseOut }) => {
return (
<div onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>
Hover Me
</div>
);
};
const HoverText = () => {
return (
<div>
Hovering right meow!
<span role="img" aria-label="cat">
🐱
</span>
</div>
);
};
const HoverExample = () => {
const [isHovering, setIsHovering] = useState(false);
const handleMouseOver = () => {
setIsHovering(true);
};
const handleMouseOut = () => {
setIsHovering(false);
};
return (
<div>
{/* Hover over this div to hide/show <HoverText /> */}
<HoverableDiv
handleMouseOver={handleMouseOver}
handleMouseOut={handleMouseOut}
/>
{isHovering && <HoverText />}
</div>
);
};
class:
import React, { Component } from "react";
import { render } from "react-dom";
const HoverableDiv = React.memo(({ handleMouseOver, handleMouseOut }) => {
return (
<div onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>
Hover Me
</div>
);
});
const HoverText = () => {
return (
<div>
Hovering right meow!
<span role="img" aria-label="cat">
🐱
</span>
</div>
);
};
class HoverExample extends Component {
constructor(props) {
super(props);
this.handleMouseOver = this.handleMouseOver.bind(this);
this.handleMouseOut = this.handleMouseOut.bind(this);
this.state = {
isHovering: false
};
}
handleMouseOver() {
this.setState(() => ({
isHovering: true
}));
}
handleMouseOut() {
this.setState(() => ({
isHovering: false
}));
}
render() {
return (
<div>
{/* <HoverText /> gets shown when mouse is over <HoverableDiv /> */}
<HoverableDiv
handleMouseOver={this.handleMouseOver}
handleMouseOut={this.handleMouseOut}
/>
{this.state.isHovering && <HoverText />}
</div>
);
}
}