CSS 在 reactjs 中悬停时显示组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44566340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show a component on hover in reactjs
提问by R. Meier
I've created several sections with the heading of the specific content.
我创建了几个带有特定内容标题的部分。
I want to show a short sneak preview on hovering above the different section.
我想在悬停在不同部分上方时显示一个简短的预览。
Does anyone knows how to create a hoverActionHandler with conditional rendering of a react component?
有谁知道如何创建带有条件渲染反应组件的 hoverActionHandler ?
回答by Ben Bud
You can use onMouseEnter
and onMouseLeave
to change the state and render a component conditionally based on the value of the state.
您可以使用onMouseEnter
和onMouseLeave
来更改状态并根据状态值有条件地渲染组件。
See it in action: https://codesandbox.io/s/XopkqJ5oV
看看它在行动:https: //codesandbox.io/s/XopkqJ5oV
import React, { Component } from 'react';
class HoverExample extends Component {
constructor(props) {
super(props);
this.handleMouseHover = this.handleMouseHover.bind(this);
this.state = {
isHovering: false,
};
}
handleMouseHover() {
this.setState(this.toggleHoverState);
}
toggleHoverState(state) {
return {
isHovering: !state.isHovering,
};
}
render() {
return (
<div>
<div
onMouseEnter={this.handleMouseHover}
onMouseLeave={this.handleMouseHover}
>
Hover Me
</div>
{
this.state.isHovering &&
<div>
Hovering right meow!
</div>
}
</div>
);
}
}