next.js - 如何使用 NextJS 和 TailwindCSS 更改悬停图像?
问题描述
我正在尝试获取一个使用 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>
);
}
解决方案
只是为您和您当前的实施提供了一些额外的信息
目前,您的导航会在每个徽标图像悬停时重新呈现。由于状态变化,将徽标组件移出导航将阻止整个导航组件在每次悬停时重新渲染。
在您的情况下,您不需要前向引用 - 我在示例中留下了前向引用,因为您可以在技术上使链接组件成为全局可重用组件。
您将无法在自定义下一个/链接上设置大多数可用的下一个/链接道具选项。
这是一个稍微修改的版本,可以解决这些问题。
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>
);
}
推荐阅读
- javascript - 一个包含图像的javascript文件?
- php - 通过连接和标题('Content-Type:audio/mpeg')使用php合并mp3音频是否正确?
- visual-studio-code - 在 VS Code 中,有没有办法在用右括号 (}) 关闭代码块时自动添加结束注释?
- android - Android - 如何创建一个包含许多布局的 ScrollView?
- java - 在二维数组的所需位置插入列
- c# - 如何打包 PowerShell 二进制 Cmdlet 以从 Azure DevOps 库安装
- sql - athena presto - 从长到宽的多列
- prisma-graphql - 在 Prisma 2 中检索已删除模型的相关模型
- java - 使用其中一个面板内的按钮在面板之间切换
- python - 使用异步的进程间通信?