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

Ben*_* Li 7 hover mouseevent mouseenter mouseleave 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} />
    }
Run Code Online (Sandbox Code Playgroud)

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

我也尝试过css解决方案,当我将鼠标悬停在图像上时,更改不透明度属性.但问题是一样的:当我在图像中移动鼠标时,:悬停而不是悬停被多次触发.

怎么解决这个?谢谢


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

Rob*_*jre 16

使用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>
        }
    
    Run Code Online (Sandbox Code Playgroud)


pro*_*sti 7

我真的认为你只能在CSS中实现这一点.因此,您的组件应具有简单className属性,并且该类应具有以下定义:

.image-hover-opacity:hover {
  opacity: 0.5;
}
Run Code Online (Sandbox Code Playgroud)

class Example extends React.Component {
  constructor() {
    super();
    this.state = {};
  }
    

  render() {
    return(
      <img className="image-hover-opacity" src="http://i.imgur.com/PLKabDV.png" />
    );
  }
}

ReactDOM.render(<Example />, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)
.image-hover-opacity:hover {
  opacity: 0.5;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Run Code Online (Sandbox Code Playgroud)