如何在ReactJS中悬停时添加特定图像的样式?



问题是我想为图像添加边框并显示卡片它包含悬停时的信息,但它显示到所有的图像。

从电影API获取数据后,我将响应存储在状态:

const [movies, setMovies] = useState([])
useEffect(() => {
/**side-effects**/
setMovies(response.data)

},[])

然后

let style = {
display: 'none'
};
let imgStyle = {};
if(hover){
style = {
display: 'block'
}
imgStyle = {
border: 1px solid white
}
}
if(movies.length > 1) {
display = (
<div className="MovieContainer">
<h2>Trending this week</h2>
<Carousel>
{movies.map((movie) => {
return (
<>
<img
style={imgStyle}
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}
className="Images"
key={movie.id}
src={movie.image}
alt={movie.title}
/>
<Card style={style}>{movie.title}</Card>
</>
);
})}
</Carousel>
</div>
);
}
but instead of adding a style to the *hovered* image, it also adds the style to all images.
I also tried using css for the border and it works the way I wanted but I couldn't think of any way for the Cards to show up when hovering 

为什么不直接在css文件中做这个修改,你可以直接添加到你的css

img:hover { "2px solid black" }

代替内联样式和使用onMouseEnteronMouseLeave

最新更新