小编典典

在React中,onMouseEnter或悬停无法按预期工作

reactjs

opacity = 1开始我有一张图片。

当鼠标进入图像时,更改opacity = 0.5。当鼠标离开图像时,将不透明度改回来。

这是一个代码:

mouseEnter() {
    console.log('mouse enter')
    const classname = '.' + this.props.post.code
    document.querySelector(classname).classList.add('image-hover-opacity')
}

mouseLeave() {
    console.log('mouse leave')
    const classname = '.' + this.props.post.code
    document.querySelector(classname).classList.remove('image-hover-opacity')
}

    render() {
        <img src={src} onMouseEnter={::this.mouseEnter} onMouseLeave={::this.mouseLeave} />
    }

当鼠标进入和离开图像时,分别触发onMouseEnter和onMouseLeave良好。但是问题是当我在图像中移动鼠标时,会触发onMouseEnter和onMouseLeave。

我也尝试了css解决方案,当我将鼠标悬停在图像上时,更改了opacity属性。但是问题是一样的:当我在图像中移动鼠标时,:hover和not
hover被多次触发。

如何解决呢?谢谢


更新
我之前的代码中有一些内容。创建了一个jsfiddle,它可以工作。对不起大家


阅读 1173

收藏
2020-07-22

共1个答案

小编典典

使用document.querySelector不是一种非常反应的思维方式。您可以尝试以下方法:

  • 使用div包装纸img来避免这种奇怪的mouseEnter行为
  • this.state不透明使用
        constructor() {
      this.state = {
        opacity: 1
      }
    }

    mouseEnter() {
        console.log('mouse enter')
        this.setState({opacity: 0.5})
    }

    mouseLeave() {
        console.log('mouse leave')
        this.setState({opacity: 1})
    }

        render() {
          <div style={{opacity: this.state.opacity}}>
            <img src={src} onMouseEnter={::this.mouseEnter} onMouseLeave={::this.mouseLeave} />
          </div>
        }
2020-07-22