我在工作中从事仪表板项目,需要您的帮助。 我的应用中使用了 React、nextjs 和 material-ui。 在此网站上,定义了一个菜单,其中包含用于在页面之间导航的可点击链接。
但是,我无法正确使用<Link>
来自 next/link
.
在我的应用程序中,我需要使用 <Link/>
用这样的东西:
import Foo from './foo';
[...]
<Link href="/about" passHref>
<Foo />
</Link>
[...]
<Foo/>
在另一个文件中定义并包含一个 <a>
.
即使我通过了 passHref,我的链接也无法被点击。
在现实生活中,我的应用程序更复杂并使用 material-ui 但这个真正简化的版本似乎存在问题:https://gist.github.com/Oyabi/4aea0ce2fa36029868641d147ba9e551
如果 gist 在将来被关闭或删除,这里是代码:
pages/index.jsx:
import React from "react";
import Menu from "../components/Menu";
function Home() {
return <Menu />;
}
export default Home;
组件/Menu.jsx:
import React from "react";
import Link from "next/link";
import MenuItem from "./MenuItem";
function Menu() {
return (
<Link href="/about" passHref>
<MenuItem />
</Link>
);
}
export default Menu;
组件/MenuItem.jsx:
import React from "react";
import Link from "next/link";
function MenuItem() {
return (
<div>
<a>not ok - link is not clickable even if the following lines are commented</a>
<br />
<Link href="/about" passHref>
<a>ok - link is clickable</a>
</Link>
<Link href="/about" passHref>
<a>ok - link is clickable</a>
</Link>
<Link href="/about" passHref>
<div className="useless">
foo
<a>even with something more complicated</a>
<br />
<a>the 2 links are clikable</a>
bar
</div>
</Link>
</div>
);
}
export default MenuItem;
如果我包围我的 <a>
在 <Link>
之间在同一个文件中,一切正常并按预期工作,但如果我申请 <Link>
则情况并非如此在一个组件上。
如您所见,即使我设置了 passHref
.
如何制作我的 <Link>
在 Menu.jsx
工作?
问候。
最佳答案
尝试用这样的 fragment
替换周围的 div
:
function MenuItem() {
return (
<> // here
<a>not ok - link is not clickable even if the following lines are commented</a>
<br />
<Link href="/about" passHref>
<a>ok - link is clickable</a>
</Link>
<Link href="/about" passHref>
<a>ok - link is clickable</a>
</Link>
<Link href="/about" passHref>
<div className="useless">
foo
<a>even with something more complicated</a>
<br />
<a>the 2 links are clikable</a>
bar
</div>
</Link>
</> // and here
);
}
关于javascript - <Link> 不会在 child 中传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56083424/