[英]Add/Modify className Dynamically onMouseEnter
I want to add a new className when the user hovers on a slick slider Image and perform some CSS transition for that particular Image card in the slider.当用户将鼠标悬停在光滑的滑块图像上并为滑块中的特定图像卡执行一些CSS转换时,我想添加一个新的className 。 https://stackblitz.com/edit/react-slick-slider-issues how do I add className to the slider whenever the user hovers on the image or change the parent className based on the hover position?
https://stackblitz.com/edit/react-slick-slider-issues每当用户悬停在图像上或根据悬停位置更改父类名称时,如何将className添加到滑块?
I tried the document.getElementsByClassName('unique-image') but all the images have this className as they are looped inside a map function.我尝试了document.getElementsByClassName('unique-image')但所有图像都有这个 className 因为它们在map函数中循环。 how can I only change unique-image className if the user hovers on a certain image to unique-image-hover ?
如果用户将鼠标悬停在某个图像上,我如何才能将unique-image className 更改为unique-image-hover ?
You may access Event.target
that triggered mouseEnter
and use Element.classList
add()
method to add your desired className
您可以访问
Event.target
触发mouseEnter
和使用Element.classList
add()
方法添加所需className
So, your mouseEnter
handler may look like that:因此,您的
mouseEnter
处理程序可能如下所示:
const mouseHover = e =>{
e.target.classList.add('someClassNameYouWantedToAdd')
}
I can use React.useState我可以使用 React.useState
const [hoveredClass, setHoveredClass] = React.useState("");
const updateHovered = (e) => {
setHoveredClass(e.target.id)
}
const removeHovered = (e) => {
setHoveredClass('')
}
return (
<div className={`someStaticClass ${hoveredClass ? "hoveredClass" : ""}`}
onMouseEnter={updateHovered}
onMouseExit={removeHovered}
>
{list. map(item => (
<ImageChildComponent {...item} />
)}
</div>
)
Target will give you a child element, but you can add an event listener to the parent. Target 将为您提供一个子元素,但您可以向父元素添加一个事件侦听器。
As @YevgenGorbunkov mention, change in state will trigger rerendering, so consider wrapping ImageChildComponent with React memo to prevent unnecessary rendering正如@YevgenGorbunkov 提到的,状态变化会触发重新渲染,所以考虑用React memo包装 ImageChildComponent 以防止不必要的渲染
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.