我已经创建了几个章节,标题是具体内容.
我想展示一个在不同区域上方悬停的简短预览.
有人知道如何创建带有条件呈现的Resact组件的hoverActionHandler吗?
我已经创建了几个章节,标题是具体内容.
我想展示一个在不同区域上方悬停的简短预览.
有人知道如何创建带有条件呈现的Resact组件的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>
);
};
课程:
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>
);
}
}