0

I have a link to a codepen and the problem is best observed in Chrome:

https://codepen.io/pkroupoderov/pen/jdRowv

The mouseLeave event does not fire sometimes when a user quickly moves the mouse over multiple images, meaning that some images will still have the grayscale filter applied. How to fix that? If I use a div instead of an anchor element it works totally fine. Should I slightly change the markup or apply certain styles to the anchor element?

I'm trying to create an overlay effect on an image when a user hovers over one just like on Instagram. I will add the content to the overlay later I just need to solve that mouseLeave event issue. CSS pseudo styles is not going to work since the overlay needs to have content in it.

const imageUrls = [
  'https://farm8.staticflickr.com/7909/33089338628_052e9e2149_z.jpg',
  'https://farm8.staticflickr.com/7894/46240285474_81642cbd37_z.jpg',
  'https://farm8.staticflickr.com/7840/32023738937_17d3cec52f_z.jpg',
  'https://farm8.staticflickr.com/7815/33089272548_fbd18ac39f_z.jpg',
  'https://farm5.staticflickr.com/4840/40000181463_6eab94e877_z.jpg',
  'https://farm8.staticflickr.com/7906/46912640552_4a7c36da63_z.jpg',
  'https://farm5.staticflickr.com/4897/46912634852_93440c416a_z.jpg',
  'https://farm5.staticflickr.com/4832/46964511231_6da8ef5ed0_z.jpg'
]

class Image extends React.Component {
  state = {hovering: false} 

  handleHover = () => {
    this.setState({hovering: true})
  }
  handleLeave = () => {
    this.setState({hovering: false})
  }

  render() {
    if (!this.state.hovering) {
      return (
        <div onMouseOver={this.handleHover}>
          <img src={this.props.url} alt='' />
        </div>
      )
    } else {
      return ( // works fine when using <div> tag instead of <a> or <span>
        <a href="#" style={{display: 'block'}} onMouseLeave={this.handleLeave}>
          <img style={{filter: 'opacity(20%)'}} src={this.props.url} alt='' />
        </a>  
      )
    }
  }
}

const Images = () => {
  return (
    <div className="gallery">  
      {imageUrls.map((image, i) => {
        return <Image key={i} url={image} />
      })}
    </div>
  )
}

ReactDOM.render(<Images />, document.getElementById('app'))
4

1 回答 1

1

我的猜测是你的鼠标在它能够将新元素重新呈现到页面之前离开了组件。我建议不要有条件地将不同的元素呈现到组件中,而只是使用条件在标签内以不同的方式呈现样式。

我的解决方案是将 Image 组件中的渲染函数更改为这样的

render() {
  return ( // works fine when using <div> tag instead of <a> or <span>
    <a href="#" style={{display: 'block'}} onMouseLeave={this.handleLeave} onMouseOver={this.handleHover}>
      <img style={{filter: this.state.hovering ? 'opacity(20%)' : 'none'}} src={this.props.url} alt='' />
    </a>  
  )
}

https://codepen.io/anon/pen/GzaGgq

于 2019-02-21T16:37:02.033 回答