首页 > 解决方案 > 如何使用 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>
  );
}

标签: next.jstailwind-css

解决方案


只是为您和您当前的实施提供了一些额外的信息

目前,您的导航会在每个徽标图像悬停时重新呈现。由于状态变化,将徽标组件移出导航将阻止整个导航组件在每次悬停时重新渲染。

在您的情况下,您不需要前向引用 - 我在示例中留下了前向引用,因为您可以在技术上使链接组件成为全局可重用组件。

您将无法在自定义下一个/链接上设置大多数可用的下一个/链接道具选项。

这是一个稍微修改的版本,可以解决这些问题。

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>
  );
}

推荐阅读