在 React 中,onMouseEnter 或悬停未按预期工作未按、工作、React、onMouseEnter

由网友(Die schönsten(最漂亮))分享简介:我有一张以 opacity = 1 开头的图像.I have one image with opacity = 1 at the beginning.当鼠标进入图像时,改变opacity = 0.5.当鼠标离开图像时,将不透明度改回来.When mouse enters the image, change opa...

我有一张以 opacity = 1 开头的图像.

I have one image with opacity = 1 at the beginning.

当鼠标进入图像时,改变opacity = 0.5.当鼠标离开图像时,将不透明度改回来.

When mouse enters the image, change opacity = 0.5. When mouse leaves the image, change the opacity back.

这是一个代码:

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 都会被触发.

onMouseEnter and onMouseLeave are fired when mouse enters and leaves the image, respectively, good. But the problem is when I move the mouse inside the image, both onMouseEnter and onMouseLeave are fired.

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

And I have tried css solution as well, when I hover on image, change the opacity property. But the problem is the same: when I move mouse inside the image, :hover and not hover are fired multiple times.

如何解决这个问题?谢谢

How to solve this? thanks

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

UPDATE There is something in my previous code. Created one jsfiddle, and it works. sorry guys

推荐答案

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

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

使用 div 包装此 img 以避免这种奇怪的 mouseEnter 行为

使用带有不透明度的 this.state 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>
    }

阅读全文

相关推荐

最新文章