onMouseEnter和onMouseLeave无法按预期运行

时间:2017-07-22 20:34:32

标签: javascript css reactjs

我正在尝试为我的组件模拟悬停效果。然而,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;
}

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

在你的css中你有pointer-events: none;,这会禁用鼠标事件的发生。删除它们,它的工作原理。

fiddle

.OnScrollComp {
  border-style: solid;
  border-color: black;
  border-width: thick;
  width: 600px;
  height: 300px;
  opacity: 0;
  transition: opacity 3s;
}



.OnScrollComp.visible {
  opacity: 1;
}