进行内联样式设置时,如何在ReactJS中实现悬停事件或活动事件?
我发现onMouseEnter和onMouseLeave方法存在问题,因此希望有另一种方法可以做到。
具体来说,如果您将鼠标悬停在组件上非常快,则仅会注册onMouseEnter事件。onMouseLeave永远不会触发,因此无法更新状态...使该组件看起来好像仍在悬停。如果您尝试模仿“:active” css伪类,我会注意到同样的事情。如果单击得非常快,则只会注册onMouseDown事件。onMouseUp事件将被忽略...使组件保持活动状态。
这是显示问题的JSFiddle:https ://jsfiddle.net/y9swecyu/5/
有问题的JSFiddle视频:https ://vid.me/ZJEO
代码:
var Hover = React.createClass({
getInitialState: function() {
return {
hover: false
};
},
onMouseEnterHandler: function() {
this.setState({
hover: true
});
console.log('enter');
},
onMouseLeaveHandler: function() {
this.setState({
hover: false
});
console.log('leave');
},
render: function() {
var inner = normal;
if(this.state.hover) {
inner = hover;
}
return (
<div style={outer}>
<div style={inner}
onMouseEnter={this.onMouseEnterHandler}
onMouseLeave={this.onMouseLeaveHandler} >
{this.props.children}
</div>
</div>
);
}
});
var outer = {
height: '120px',
width: '200px',
margin: '100px',
backgroundColor: 'green',
cursor: 'pointer',
position: 'relative'
}
var normal = {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'red',
opacity: 0
}
var hover = {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'red',
opacity: 1
}
React.render(
<Hover></Hover>,
document.getElementById('container')
)
我可以建议您一个易于理解的示例,我在React JS中使用情感来赋予样式。在这里您可以找到有关它的更多信息https://emotion.sh/docs/introduction希望对您有所帮助。