加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 在React中,onMouseEnter或hover未按预期工作

发布时间:2020-12-15 09:33:24 所属栏目:百科 来源:网络整理
导读:我有一个图像,开始时opacity = 1. 当鼠标进入图像时,更改不透明度= 0.5.当鼠标离开图像时,请更改不透明度. 这是一个代码: mouseEnter() { console.log('mouse enter') const classname = '.' + this.props.post.code document.querySelector(classname).cla
我有一个图像,开始时opacity = 1.

当鼠标进入图像时,更改不透明度= 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解决方案,当我将鼠标悬停在图像上时,更改不透明度属性.但问题是一样的:当我在图像中移动鼠标时,:悬停而不是悬停被多次触发.

怎么解决这个?谢谢

UPDATE
我以前的代码中有一些东西.创建一个jsfiddle,它的工作原理.
对不起大家

解决方法

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

>使用包装此img的div来避免这种奇怪的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>
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读