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

查看:35
本文介绍了在 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.

如何解决这个问题?谢谢

How to solve this? thanks

更新我以前的代码中有一些东西.创建了一个 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天全站免登陆