图像有条件呈现时React中的图像闪烁问题
我有一个标题,并且当鼠标悬停在标题上时,我想在其右侧显示图像。图像有条件呈现时React中的图像闪烁问题
我保持一个变量编辑模式中设置为true /状态假
那么我有条件地渲染使用onmouseover和onMouse事件的图像。
现在,当我将鼠标悬停在标题,编辑模式设置为true,图像显示出来,当我将光标移出表头的,在编辑模式下设置为false,图像消失。
我保持状态的变量编辑模式被设置为真/假consditionally渲染使用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/
如何阻止这种闪烁。 我也尝试使用onMouseEnter和onMouseLeave建议here但它没有奏效。我不知道如何,但使用这两个事件导致与我想要的相反。组件第一次加载时,一切都很好,但只要我将鼠标悬停在图标上,整个动态就会改变。当鼠标不在标题上时该图标显示,并且当鼠标悬停在标题上时,该图标不会显示。请帮助
与OnMouseEnter在和OnMouseLeave在代码是在这里:http://jsfiddle.net/Lu4w4v1c/3/
当你有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>
如果您有打算做呈现一个div里面,你应该使用OnMouseLeave在onmouseover事件的容器。示例小提琴也有onmouseleave。
https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_mouseleave_mouseout
这说明了什么问题
我不知道为什么,但您的解决方案是工作在小提琴,但不是在我的代码库:对。你为什么mouseEnter和mouseLeave事件不起作用? – Swapnil
我也写过解释。 “当您将鼠标悬停在图像上时,它会响应标题的mouseout事件并立即隐藏图像,从而在h3上触发鼠标悬停,从而导致闪烁行为。” – jssridhar