在React中,onMouseEnter或悬停无法按预期工作 [英] In React, onMouseEnter or hover is not working as expected

查看:847
本文介绍了在React中,onMouseEnter或悬停无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一幅图像的开头是opacity = 1.

I have one image with opacity = 1 at the beginning.

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

When mouse enters the image, change opacity = 0.5. When mouse leaves the image, change the opacity back.

这是一个代码:

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.

onMouseEnter and onMouseLeave are fired when mouse enters and leaves the image, respectively, good. But the problem is when I move the mouse inside the image, both onMouseEnter and onMouseLeave are fired.

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

And I have tried css solution as well, when I hover on image, change the opacity property. But the problem is the same: when I move mouse inside the image, :hover and not hover are fired multiple times.

该如何解决?谢谢

更新 我之前的代码中有一些内容.创建了一个 jsfiddle ,它可以正常工作. 抱歉

UPDATE There is something in my previous code. Created one jsfiddle, and it works. sorry guys

推荐答案

使用document.querySelector并不是一种非常React的思维方式.您可以尝试这种方法:

Using document.querySelector is not a very React way of thinking. You can try this approach:

  • 使用div包装此img以避免这种奇怪的mouseEnter行为
  • 使用this.state不透明

  • Use a div wrapping this img to avoid this weird mouseEnter behavior
  • Use this.state with opacity

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>
    }

这篇关于在React中,onMouseEnter或悬停无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆