【问题标题】:<Link> does not work as expected in NextJS<Link> 在 NextJS 中无法按预期工作
【发布时间】:2021-11-20 00:34:05
【问题描述】:

我正在创建一个 Next.js 应用程序,其中一部分需要我在单击卡片组件时创建动态路由。但是,在使用 Next.js 中的 &lt;Link&gt; 包装我的卡片后,我无法导航到该页面,因为单击时没有任何反应。我尝试在我的Link 下添加一个&lt;a&gt; 标签并且它有效。我来自 react-router,觉得只需添加 &lt;Link&gt; 就可以帮助导航。有人能解释一下 Link 组件中需要&lt;a&gt; 标签吗?

下面是我的代码:

import React from 'react';
import OptionsDropdown from './components/OptionsDropdown';
import Card from './components/card';
import Link from 'next/link';

const Browse = () => {
  let filterByMenuEl = ['All items', 'Single items', 'Bundles'];
  let sortByMenuEl = ['Price: Low to High', 'Price: High to Low', 'Most Favorited'];
  let card1 = {
    name: 'Collectible 1',
    description: 'This is a description',
    price: '0.11',
    img: 'https://lh3.googleusercontent.com/Fviz0PWzUMQ98uvUZV8e_3y2R3D0nwk9q3jCQONoA2jh83vN2phkxEmLD3zpE1iiPOWNqh38rCqOC4agChgi704d0VGjgqwXrjiZ1Q=w600',
    list_date: 'here'
  }
  let card2 = {
    name: 'Collectible 2',
    description: 'This is a description',
    price: '0.12',
    img: 'https://lh3.googleusercontent.com/8pQQRseehVjJ5PRZkXANawtaCooQfdTF9Ld3UvJVXxVaiixxM9x357NqLwFqindvDlKZ-XqbLytwzL-LxpiDPgJLIqOq5OHjhg5PAQ=w600',
    list_date: 'here'
  }
  let card3 = {
    name: 'Collectible 3',
    description: 'This is a description',
    price: '0.13',
    img: 'https://lh3.googleusercontent.com/a2w4nmFDYU1Z5kimGQtymbw7E-Jj8zrZRGiKmkmv03e9z5VJAFFqSIsvq39EjtlETwluC9hDGx6EpS5YOCVN6X6pTlAiOpuD5tYW=w600',
    list_date: 'here'
  }
  let card4 = {
    name: 'Collectible 4',
    description: 'This is a description',
    price: '0.14',
    img: 'https://lh3.googleusercontent.com/P0FjJQ-9_YlBUtl6-pg5tgz1KUOqxgGRnB0u4v3C6YnY14cMWealXb5u3O2OI_Zr-YxMYaRs_b4TVrBTZzXF18_zhZ1WWPsBYj6xyg=w600',
    list_date: 'here'
  }
  let card5 = {
    name: 'Collectible 5',
    description: 'This is a description',
    price: '0.15',
    img: 'https://lh3.googleusercontent.com/alrw4OsjldeYC5WpJCfneeui2F4lNDU0xYLp80LA9horlf7wufhRG_2ln5u72PLaNh9tF_3WqSXZoCFTgIC9GatkKPobLQ5zYJgrug=w600',
    list_date: 'here'
  }
  let card6 = {
    name: 'Collectible 6',
    description: 'This is a description',
    price: '0.16',
    img: 'https://lh3.googleusercontent.com/lGp0y5VfF0j0gpe9OcY34inan58xkJuH6i6vCtCempSbUBMsF0cXexO_rFJNixIQP3n27M0L1waBS8oUI_JayefpzmB9Lw3q5oq6=w600',
    list_date: 'here'
  }

  let cards = [card1, card2, card3, card4, card5, card6];

  return(
    <div className='BrowsePage'>
      <div className='browse-options'>
        <div className='browse-results'>100,000 results</div>
        {/* <div className='options-spacer' /> */}
        <div className='browse-dropdowns'>
          <OptionsDropdown title='Filter by' menuEl={filterByMenuEl} />
          <OptionsDropdown title='Sort by' menuEl={sortByMenuEl} />
        </div>
      </div>
      <div className='browse-main'>
        {cards.map((e, index) => {
          return (
          <Link href={"/browse/" + e.name} key = {e.name} passHref={true}>
              <Card
              key={index}
              name={e.name}
              description={e.description}
              price={e.price}
              img={e.img}
            />
          </Link>
          )
        })}
      </div>
    </div> 
  );
} 

export default Browse;

【问题讨论】:

  • 这是否回答了您的问题:NextJS Link isn't rendering an anchor tag?这是预期的行为,您必须使用 &lt;a&gt; 标记包装子组件。
  • 你能检查浏览器的 html 并查看 href 是什么吗?

标签: javascript reactjs next.js


【解决方案1】:

有人能解释一下 Link 组件中需要一个标签吗?

如果子项不是字符串,则需要在 Next.js 链接组件中使用 &lt;a&gt; 标记。否则你不需要&lt;a&gt; 标签。见:NextJS Link isn't rendering an anchor tag 来自:https://github.com/vercel/next.js/blob/canary/packages/next/client/link.tsx

关于&lt;a&gt;标签的一些想法:

  1. 每个&lt;a&gt; 中的内容应指明链接的目的地。如果存在 href 属性,则在关注 &lt;a&gt; 元素时按下回车键将激活它。见:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a

  2. &lt;a&gt; 是一个标签,它允许右键单击其中的其他元素,并具有“在新选项卡中打开链接”、“复制链接地址”等选项。(这就是我使用这个组件的原因。)

【讨论】:

    【解决方案2】:

    我认为问题出在您的 slug 路由中。 请查看下一个文档,其中描述了带有动态段的路线。

    function Posts({ posts }) {
      return (
        <ul>
          {posts.map((post) => (
            <li key={post.id}>
              <Link href={`/blog/${encodeURIComponent(post.slug)}`}>
                <a>{post.title}</a>
              </Link>
            </li>
          ))}
        </ul>
      )
    }
    

    【讨论】:

    • 如果你将它包裹在a标签周围,请确保将'passHref`添加到Link上
    • 如果Link 的孩子是&lt;a&gt;,则不需要使用passHref。只有在包装&lt;a&gt; 标签本身的组件上使用Link 时才应该这样做。以上将正常工作。
    【解决方案3】:

    不确定您的问题到底是什么,但这里是您如何使用动态下一个/链接:

    {myArray.map((item) => (
     <NextLink href={`/something/${item.slug}`} passHref>
         <a href={`/something/${item.slug}`}>
             Dynamic link for {item.id}
          </a>
    </NextLink>
    ))}
    

    快速如何:

    1. 将 NextLink 包裹在 a 标签周围
    2. 在两者上添加href 属性
    3. 在 NextLink 上添加 passHref 属性以避免在 html 中呈现 2 个标签

    【讨论】:

    • 如果孩子是&lt;a&gt; 标签,则无需使用passHref。您也不需要(也不应该)在&lt;a&gt; 标签上设置href
    • 不,如果孩子是&lt;a&gt; 标签(如您的示例中),则不需要使用passHref。如果子组件是包装&lt;a&gt; 的组件,您确实需要
    猜你喜欢
    • 1970-01-01
    • 2019-12-18
    • 2022-12-31
    • 2013-12-23
    • 2014-12-09
    • 2016-01-13
    • 2020-09-21
    • 2011-08-17
    • 2012-04-29
    相关资源
    最近更新 更多