问题
I have this image :
As you can see, there is a red x button created in css. I have created methods for onMouseEnter
and onMouseLeave
, and when I hover over the green image, I want the red x to appear, which has a delete functionality. The problem is, when I hover on the green image the red cross appears, but when I hover over the red one to press it, it disappears randomly and I don't know why. I need to fix it in react not using mainly css.
code.js:
const handleMouseOver = () => {
const isToggle = true
setToggleDiv(isToggle)
}
const handleMouseOut = () => {
const isToggle = false
setToggleDiv(isToggle)
}
<div>
<h3>preview items</h3>
<div className="image" onMouseEnter={handleMouseOver} onMouseLeave={handleMouseOut}>
<img src={myUrl} />
{toggleDiv === true ?
<div className="delete" type="button" onClick={() => handleDelete(myPhotoId)}>
X
</div> : null}
<div>{myPohotTitle}</div>
</div>
css:
.image {
position: relative;
width: 50px;
margin: 0px auto;
}
.delete {
background-color: red;
width: 30px;
padding: 10px;
color: white;
display: flex;
cursor: pointer;
position: absolute;
top: 0;
right: 0;
}
回答1:
You just need to change onMouseLeave
with onMouseOut
and it will work just fine.
EDIT:
Even a better way , much easier without any methods:
export default () => {
return (
<div>
<h3>preview items</h3>
<div className="image">
<img src={myUrl} />
<div className="delete" type="button" onClick={() => handleDelete(myPhotoId)}>
X
</div>
<div>{myPohotTitle}</div>
</div>
</div>
)
}
and your css
.image {
position: relative;
width: 50px;
margin: 0px auto;
}
.delete {
background-color: red;
width: 30px;
padding: 10px;
color: white;
display: none;
cursor: pointer;
position: absolute;
top: 0;
right: 0;
}
.image:hover > .delete {
display: flex;
}
来源:https://stackoverflow.com/questions/62281453/how-to-fix-hover-method