鼠标移入和移出事件(onMouseEnter和onMouseLeave)未如预期般运作

3

我正在尝试模拟组件的悬停效果。然而, onMouseEnter / Leave 事件并没有按照预期工作,目前我正在尝试使它简单地 console.log 一个字符串来检查它是否起作用,但什么都没有发生。目标是在悬停时更改其背景颜色;我尝试通过 CSS 类:hover 进行设置,但没有成功。如何使 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
@hyper0009 这是因为 T4rk1n 在渲染组件时添加了 widthheightbackground-color。请在他的 fiddle 中检查您的组件的渲染方法。 - DavidDomain
@DavidDomain 实际上,我读得太快了,只复制了js而没有css,并修改了div以包含样式。当我添加了css和原始代码后,它就无法工作了。 - T4rk1n
@T4rk1n 哦,好的。不过你已经修复了它。;) 请继续将其发布为答案。 - DavidDomain
@DavidDomain,那不是问题,我已经得到了真正的答案。 - T4rk1n
@DavidDomain,你说得对,将CSS添加到fiddle中会破坏它,我已经为此苦恼了一段时间,期待着答案的出现 :) - hyper0009
1个回答

4
在你的CSS中,你使用了pointer-events: none;,这会禁止鼠标事件发生。将其删除即可使其正常工作。 示例
.OnScrollComp {
  border-style: solid;
  border-color: black;
  border-width: thick;
  width: 600px;
  height: 300px;
  opacity: 0;
  transition: opacity 3s;
}



.OnScrollComp.visible {
  opacity: 1;
}

哇,我简直不敢相信;非常感谢;这解决了问题!@T4rk1n - hyper0009

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接