javascript - <Link> 不会在 child 中传播

标签 javascript reactjs next.js

我在工作中从事仪表板项目,需要您的帮助。 我的应用中使用了 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/

相关文章:

node.js - NextJS 和 React : Cannot read property 'email' of undefined

next.js - 如何在部署到 Vercel 的 Next js 中禁用目录列表

javascript - 将 JSON 文件中的数据加载到 Google map 中的 map 标记中

javascript - 在嵌套的 js 对象数组中搜索

javascript - JavaScript block 中的 @ 符号

reactjs - 如何设计 Redux 存储和操作?

javascript - 如何修复 "TypeError: this.getElement(...) is null"

javascript - 如何转义像 "\\r\\n "这样的清理字符串

javascript - React JS 中 Clicked 事件发生的元素添加 Class

next.js - 将数据从 NextJS 中的上一页传递给 getServerSideProps