我试图将鼠标悬停在每个图像上,并为每个图像显示不同的内容(本例中为图像或文本(。
现在,当我将鼠标悬停在图像上时,它会更改为所有图像。我知道我必须使用一个事件,但不确定如何使用钩子。
const Logos = () => {
const [defaultImg, setNewImg] = useState("image1");
const onMouseLeave = (e) => {
console.log(e.target, "img leave");
setNewImg("image1");
};
const onMouseEnter = (e) => {
console.log(e.target, "enter");
setNewImg("image2");
};
return (
<div className="images">
<div className="logos-container">
<h3 className="title">Trinity title goes here</h3>
<div className="logos">
{logos.map((logo) => (
<Link to="/">
<img
key={logo.image}
src={defaultImg}
alt=""
className="logo"
onMouseLeave={onMouseLeave}
onMouseEnter={onMouseEnter}
/>
</Link>
))}
</div>
</div>
</div>
);
};
您正在更改每个图像的状态,因为您将相同的defaultImg
传递给每个图像。
您可能应该将这个逻辑放在一个处理自己状态的Image
组件中。
const Image = ({ logo }) => {
const [defaultImg, setImg] = useState(BreezeLogo);
const onMouseLeave = (e) => {
console.log(e.target, "img leave");
setImg(BreezeLogo);
};
const onMouseEnter = (e) => {
console.log(e.target, "enter");
setImg(SafebridgeLogo);
};
return (
<img
key={logo.image}
src={defaultImg}
alt=""
className="logo"
onMouseLeave={onMouseLeave}
onMouseEnter={onMouseEnter}
/>
);
};
const Logos = ({ logos }) => {
return (
<div className="images">
<div className="logos-container">
<h3 className="title">Trinity title goes here</h3>
<div className="logos">
{logos.map((logo) => (
<Link to="/">
<Image logo={logo} />
</Link>
))}
</div>
</div>
</div>
);
};