【问题标题】:Image flickering issue in React when image is conditionally rendered有条件渲染图像时 React 中的图像闪烁问题
【发布时间】:2017-05-04 05:45:59
【问题描述】:

我有一个标题,当鼠标悬停在标题上时,我想在其右侧显示一个图像。

  • 我正在维护一个变量 editMode 处于设置为 true/false 的状态

  • 然后我使用 onMouseOver 和 onMouse 事件有条件地渲染图像。

现在,当我将鼠标悬停在标题上时,编辑模式设置为 true 并显示图像,当我将光标移出标题时,editMode 设置为 false 并且图像消失。

我正在维护一个变量 editMode 在设置为真/假的状态下使用 onMouseOver 和 onMouse 渲染图像:

问题:当我将鼠标悬停在编辑图标上时,它开始闪烁。

class TempComponent extends React.Component {
constructor() {
    super()
    this.editModeToggler = this.editModeToggler.bind(this)
    this.state = {
        editMode: false
    }
}

editModeToggler() {
    console.log('called')
    this.setState({editMode: !this.state.editMode})
}

render() {
  return(
    <div>
      <h3
        onMouseOut={this.editModeToggler} 
        onMouseOver={this.editModeToggler}
      >
        Title
      </h3>
      {this.state.editMode?
            <img src='http://www.rebanet.it/images/banners/iscrizioni.png' />
        :
        null
      }
    </div>
  )
 }
}

你可以在这里找到这段代码:http://jsfiddle.net/Lu4w4v1c/2/

如何停止这种闪烁。 我也尝试过按照here 的建议使用 onMouseEnter 和 onMouseLeave,但没有成功。我不知道如何使用这两个事件导致与我想要的相反。第一次加载组件时,一切都很好,但只要我将鼠标悬停在图标上,整个动态就会发生变化。当鼠标不在标题上方时图标显示,当鼠标在标题上方时图标不显示。请帮忙

onMouseEnter 和 onMouseLeave 的代码在这里:http://jsfiddle.net/Lu4w4v1c/3/

【问题讨论】:

    标签: reactjs dom-events conditional-rendering


    【解决方案1】:

    当你在 h3 上有监听器时,最初图像没有渲染,所以第一次一切似乎都工作正常,但是一旦图像被渲染并且你将鼠标悬停在图像上,它就会响应标题的 mouseout 事件并立即隐藏图像,从而触发 h3 上的鼠标悬停,从而导致闪烁行为。

    要解决您的问题,您只需将侦听器附加到容器上即可。用

    更新了你的小提琴http://jsfiddle.net/Lu4w4v1c/4/
    <div  onMouseOut={this.editModeToggler} 
        onMouseOver={this.editModeToggler}>
      <h3>
        Title
      </h3>
      {this.state.editMode?
            <img src='http://www.rebanet.it/images/banners/iscrizioni.png' />
        :
        null
      }
    </div>
    

    【讨论】:

    • 我不知道为什么,但是您的解决方案在小提琴中有效,但在我的代码库中却没有:p。你为什么 mouseEnter 和 mouseLeave 事件不起作用?
    • 我也写了解释。 “当您将鼠标悬停在图像上时,它会响应标题的 mouseout 事件并立即隐藏图像,这反过来会触发 h3 上的鼠标悬停,从而导致闪烁行为。”
    【解决方案2】:

    如果你有一个容器要执行 onmouseover 事件,在里面渲染一个 div,你应该使用 onMouseLeave。示例小提琴也有 onmouseleave。

    https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_mouseleave_mouseout

    这说明了问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 2020-08-27
      相关资源
      最近更新 更多