如何将 href 传递给 nextjs 中的 onClick 函数?

dev*_*_el 22 reactjs next.js

在下面的代码中

import Link from "next/link";

export default function IndexPage() {
  const handleClick = (path) => {
    if (path === "/about") {
      console.log("I clicked on the About Page");
    }
    if (path === "/posts") {
      console.log("I clicked on the Posts Page");
    }
  };
  return (
    <div>
      Hello World.{" "}
      <Link onClick={() => handleClick("/about")} href="/about">
        <a>About</a>
      </Link>
      <Link onClick={() => handleClick("/posts")} href="/posts">
        <a>Posts</a>
      </Link>
    </div>
  );
Run Code Online (Sandbox Code Playgroud)

每当单击“关于”或“帖子”页面时,我希望console.log单击页面名称。现在,我当前的实现没有console.log任何作用。我的代码有什么问题吗?

小智 26

您可以将 onClick 处理程序移至<a> tag.

import { useRouter } from "next/router";
import Link from "next/link";

export default function IndexPage() {
  const router = useRouter();

  const handleClick = (e, path) => {
    if (path === "/about") {
      console.log("I clicked on the About Page");
    }
    if (path === "/posts") {
      console.log("I clicked on the Posts Page");
    }
  };
  return (
    <div>
      Hello World.{" "}
      <Link href="/">
        <a onClick={(e) => handleClick(e, "/about")}>About</a>
      </Link>{" "}
      <Link href="/">
        <a onClick={(e) => handleClick(e, "/posts")}>Posts</a>
      </Link>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案不是处理这种情况的正确方法,请参阅文档https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor (2认同)

Moh*_*iya 6

2021-08 答复

NextJS中,

我做了类似的事情

 const Nav = () => {

  const handleLogoClick = async (e: React.MouseEvent<HTMLAnchorElement, MouseEvent> | undefined, url: string) => {
    e?.preventDefault();
    alert('clicked');
  };


     return (
            <a href="" onClick={(e) => handleLogoClick(e, '/')}>
              {shopData?.logo && <Logo src={shopData?.logo} loading="lazy" />}
            </a>
    )
 }
Run Code Online (Sandbox Code Playgroud)