问题
I have a header and I want to show an image on its right when the mouse is over the header.
I am maintaining a variable editMode in the state which is set to true/false
Then I am conditionally rendering the image using onMouseOver and onMouse events.
Now when I hover over the header, the edit mode is set to true and the image shows up and when I move the cursor out of the header, the editMode sets to false and the image disappears.
I am maintaining a variable editMode in the state which is set to true/false consditionally rendering the image using onMouseOver and onMouse:
Problem: When I hover over the edit icon, it starts flicker.
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>
)
}
}
You can find this code running over here: http://jsfiddle.net/Lu4w4v1c/2/
How do I stop this flickering. I have also tried using onMouseEnter and onMouseLeave as suggested here but it did not work. I dont know how but using these two events resulted in opposite of what I want. The first time the component loaded, everything was fine but as soon as I hover over the icon the whole dynamics changes. The icon shows up when the mouse is not over the header and it does not show up when the mouse is over the header. Please help
The code with onMouseEnter and onMouseLeave is over here: http://jsfiddle.net/Lu4w4v1c/3/
回答1:
When you have the listener on h3, initially the image is not rendered so for the first time everything seems to be working fine, but once the image is rendered and you hover over the image it responds to the mouseout event of the heading and hides the image immediately which in turn triggers a mouseover on the h3 resulting in the flickering behaviour.
To solve your problem you can simply attach the listener on the container. Updated your fiddle http://jsfiddle.net/Lu4w4v1c/4/ with
<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>
回答2:
If you have a container that is going to do onmouseover event that renders a div inside you should use onMouseLeave. The example fiddles has onmouseleave too.
https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_mouseleave_mouseout
this shows the problem
来源:https://stackoverflow.com/questions/41218108/image-flickering-issue-in-react-when-image-is-conditionally-rendered