在下面的代码中
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)
在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)
| 归档时间: |
|
| 查看次数: |
99251 次 |
| 最近记录: |