【问题标题】:In React, onMouseEnter or hover is not working as expected在 React 中,onMouseEnter 或悬停未按预期工作
【发布时间】:2017-06-15 16:19:42
【问题描述】:

我有一张以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} />
    }

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

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

如何解决这个问题?谢谢


更新 我以前的代码中有一些东西。创建了一个jsfiddle,它可以工作。 对不起各位

【问题讨论】:

  • Can't reproduce it。但是对于这些东西,你通常还是应该使用 CSS,也许给我们展示更多代码?
  • 你为什么不用 CSS :hover{ opaclty:0.5 }
  • @prosti 我已经尝试过 css 方式。但是当我在图像内移动鼠标时,不透明度在 0.5 和 1 之间切换
  • @BenjaminLi,我更新了它的工作示例。

标签: reactjs hover mouseevent mouseenter mouseleave


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这是迄今为止我在互联网上找到的最简单的解决方案,因此在可维护性方面也是最有效的。谢谢!
    猜你喜欢
    • 2012-04-18
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 2017-12-28
    • 2017-03-01
    • 1970-01-01
    相关资源
    最近更新 更多