我正在尝试使用 React.forwardRef 和 NextJS Link 在悬停时更改为不同的图像并仍然工作的徽标。
这在 CSS 中相当简单,但我一直在思考如何在 NextJS/Tailwind 世界中做到这一点。
目前我正在接受 hover: animate-pulse
...
感谢帮助!
import React from "react";
import Link from "next/link";
import Image from "next/image";
const MyLogo = React.forwardRef(({ onClick, href }, ref) => {
return (
<a href={href} onClick={onClick} ref={ref}>
<Image src="/logo1.png" width={88} height={77} alt="logo" />
</a>
);
});
export default function Nav() {
return (
<nav className="flex items-center justify-between flex-wrap bg-raisin-black p-6">
<div className="flex items-center flex-shrink-0 mr-6 cursor-pointer hover:animate-pulse">
<Link href="/">
<MyLogo />
</Link>
</div>
</nav>
);
}
答案 0 :(得分:1)
为您和您当前的实施提供一些额外信息
目前,您的导航会在每个徽标图像悬停时重新呈现。将徽标组件从导航中移出将阻止整个导航组件因状态更改而在每次悬停时重新呈现。
在您的情况下,您不需要前向引用 - 我在示例中保留了前向引用,因为您可以在技术上使链接组件成为全局可重用组件。
您无法在自定义下一个/链接上设置大多数可用的下一个/链接道具选项。
这是一个稍微修改过的版本,解决了这些问题。
import React, { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
const MyLink = React.forwardRef(
(
{ as, children, href, replace, scroll, shallow, passHref, ...rest }, // extract all next/link props and pass the rest to the anchor tag
ref,
) => (
<Link as={as} href={href} passHref={passHref} replace={replace}>
<a {...rest} ref={ref}>
{children}
</a>
</Link>
),
);
const Logo = () => {
const [isHovering, setIsHovered] = useState(false);
const onMouseEnter = () => setIsHovered(true);
const onMouseLeave = () => setIsHovered(false);
return (
<div
className="flex items-center flex-shrink-0 mr-6 cursor-pointer"
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
<MyLink href="/">
{isHovering ? (
<Image src="/logo4.png" width={88} height={77} alt="logo" />
) : (
<Image src="/logo1.png" width={88} height={77} alt="logo" />
)}
</MyLink>
</div>
);
};
export default function Nav() {
return (
<nav className="flex items-center justify-between flex-wrap bg-raisin-black p-6">
<Logo />
</nav>
);
}
答案 1 :(得分:0)
感谢 Sean W 的建议阅读,我的解决方案:
import React, { useState } from "react";
import Link from "next/link";
import Image from "next/image";
const MyLogo = React.forwardRef(({ onClick, href }, ref) => {
return (
<a href={href} onClick={onClick} ref={ref}>
<Image src="/logo1.png" width={88} height={77} alt="logo" />
</a>
);
});
const MyLogoAlt = React.forwardRef(({ onClick, href }, ref) => {
return (
<a href={href} onClick={onClick} ref={ref}>
<Image src="/logo4.png" width={88} height={77} alt="logo" />
</a>
);
});
export default function Nav() {
const [isShown, setIsShown] = useState(false);
return (
<nav className="flex items-center justify-between flex-wrap bg-raisin-black p-6">
<div
className="flex items-center flex-shrink-0 mr-6 cursor-pointer"
onMouseEnter={() => setIsShown(true)}
onMouseLeave={() => setIsShown(false)}
>
{isShown && (
<Link href="/">
<MyLogoAlt />
</Link>
)}
{!isShown && (
<Link href="/">
<MyLogo />
</Link>
)}
</div>
</nav>
);
}