In React, onMouseEnter or hover is not working as expected

帅比萌擦擦* 提交于 2019-11-30 15:23:59
Robsonsjre

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

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

I really think you can achieve this in CSS only. So your component should have simple className property and that class should have the definitions for:

.image-hover-opacity:hover {
  opacity: 0.5;
}

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'));
.image-hover-opacity:hover {
  opacity: 0.5;
}
<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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!