【问题标题】:Using Gatsby Link to navigate to MDX rendered pages使用 Gatsby Link 导航到 MDX 渲染页面
【发布时间】:2021-04-19 19:14:39
【问题描述】:

我正在寻找链接到博客文章。

import React from "react";
import styled from "@emotion/styled";
import { css } from "@emotion/react";
import { Link, Button } from "gatsby";
import Image from "gatsby-image";
import { navigate } from "@reach/router";

const BlogArticle = styled.article`
  border-bottom: 1px solid #ddd;
  display: flex;
  margin-top: 0;
  padding-bottom: 1rem;

  :first-of-type {
    margin-top: 1rem;
  }
`;

const ImageLink = styled("div")`
  margin: 1rem 1rem 0 0;
  width: 100px;
`;

const ReadNavigate = styled(Link)`
  display: inline-block;
  font-size: 0.8rem;
  font-family: "Oswald";
`;

const TutorialPreview = ({ post }) => {
  console.log(post.slug);
  return (
    <BlogArticle>
      <ImageLink onClick={() => navigate(post.slug)}>
        <Image
          fluid={post.image.sharp.fluid}
          css={css`
            * {
              margin-top: 0;
            }
          `}
          alt={post.title}
        />
      </ImageLink>
      <div
        css={css`
          padding-top: 1rem;
        `}
      >
        <h3 onClick={() => navigate(post.slug)}>{post.title}</h3>
        <p>{post.excerpt}</p>
        <ReadNavigate to="/tire-machine-basics">
          &rarr; Read this post
        </ReadNavigate>
      </div>
    </BlogArticle>
  );
};

export default TutorialPreview;

以上是我在主页上预览的模板,它适用于我的预览,如果页面通过链接组件的行为列出所有帖子,则假定 slug 应附加到当前页面堆栈。

例如

在主页链接 = /{post.slug}

在博客列表链接 = tutorials/{post.slug}

问题在于,帖子页面是使用未嵌套在教程中的页面级别的 slug 生成的。我尝试使用到达路由器的navigate() 方法来规避,但是在您最初使用链接组件导航到它们之前,这些页面不存在的问题。

我想知道是否有任何想法来规避这个问题而无需对路径进行硬编码,这样我就不需要单独的组件了。

【问题讨论】:

    标签: reactjs gatsby blogs reach-router mdxjs


    【解决方案1】:

    链接组件假定 slug 应该附加到当前页面 堆栈

    这不是真的。

    路径与您告诉&lt;Link&gt; 组件的内容相关。例如,在/posts 页面:

    <Link to="/about-me">
    

    将带您到localhost:8000/about-me。现在在/about-me,链接如下:

     <Link to="/posts/article-1">
    

    将带您到localhost:8000/posts/article-1。但是,在/posts/article-1 有这样的链接:

     <Link to="about-me">
    

    由于相对论,会带你到localhost:8000/posts/article-1/about-me

    您需要添加一个初始斜线 (/) 以使其与您的 slug 相关,就像这样。与标准锚点完全相同的行为 (&lt;a&gt;)。应用于您的代码:

    <Link to={`/${post.slug}`}>
    

    此外,您使用ImageLink 组件进行了奇怪的包装,如果需要,将您的内容包装在组件内,但不要更改 div 的导航行为。最好使用:

    <Link to={`/${post.slug}`}>
       <Image>
    </Link>
    

    【讨论】:

    • 非常感谢,图片链接是我玩的一些尝试,但我把它放回链接。我尝试使用模板文字进行了一次尝试,当我阅读您的回复时,我意识到我忘记在括号内执行此操作,一旦我做到了完美,感谢您的快速帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 2022-12-17
    • 2023-03-29
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多