【发布时间】:2017-12-28 18:17:33
【问题描述】:
我正在尝试为我的组件模拟悬停效果。但是,onMouseEnter / Leave 事件没有按预期工作,现在我正试图让它简单地 console.log 一个字符串来检查它是否工作但没有发生任何事情。目的是我可以在悬停时更改其背景颜色;我尝试通过 CSS 类进行设置:悬停但无济于事。如何让 OnMouseEnter / onMouseLeave 正常工作?这是代码:
import React from "react"
import ReactDOM from "react-router-dom"
class OnScrollComponent extends React.Component{
constructor(props){
super(props)
this.state = {
open: false,
firstTransitionPosition: 0,
scrollAppearanceAjustment: this.props.scrollAppearanceAjustment || 250
}
this.handleScroll = this.checkForScroll.bind(this)
this.hasBeenSet = false
}
checkForScroll() {
if (window.scrollY >= this.state.firstTransitionPosition && this.hasBeenSet == false) {
console.log("this event is triggering")
console.log(this.state.firstTransitionPosition)
this.setState({open: true})
this.hasBeenSet = true
}
}
mouseEnter() {
console.log("hello, the mouse is here")
}
mouseExit() {
console.log("bye bye, the mouse is gone")
}
componentDidMount(){
var transitionComp = this.refs.moveMe
var topOfElement = transitionComp.getBoundingClientRect().top
var heightOfElement = transitionComp.getBoundingClientRect().height
this.setState({firstTransitionPosition: topOfElement - heightOfElement - this.state.scrollAppearanceAjustment}, () => {
this.checkForScroll()
});
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount(){
window.removeEventListener('scroll', this.handleScroll);
}
render(){
return(
<div ref="moveMe" onMouseEnter={this.mouseEnter} onMouseLeave={this.mouseExit}
className={`OnScrollComp ${this.state.open ? "visible" : ""}`} id={this.props.id}>
{this.props.description} {this.props.link}
</div>
)
}
}
module.exports = OnScrollComponent;
以及组件类的 CSS:
.OnScrollComp {
border-style: solid;
border-color: black;
border-width: thick;
width: 600px;
height: 300px;
opacity: 0;
transition: opacity 3s;
pointer-events:none;
}
.OnScrollComp.visible {
opacity: 1;
pointer-events:none;
}
提前感谢您的帮助!
【问题讨论】:
-
@T4rk1n 这真的很奇怪,运行实际站点时,我的 Web 控制台上没有任何输出,这怎么可能?
-
@hyper0009 这是因为 T4rk1n 在渲染组件中添加了
width、height和background-color。在他的小提琴中检查你的组件的渲染方法。 -
@DavidDomain 实际上,我读得太快了,只是复制了 js 而不是 css 并修改了 div 以包含样式。当我添加 css 和原始代码时,它不起作用。
-
@T4rk1n 啊,好的。好吧,你还是修好了。 ;) 继续并将其作为答案发布。
-
@DavidDomain 这不是问题,我得到了真正的答案。
标签: javascript css reactjs