1

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

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()到达路由器的方法,但是在您最初使用链接组件导航到它们之前,这些页面不存在的问题。

我想知道是否有关于如何绕过这个而不对路径进行硬编码的任何想法,这样我就不需要单独的组件。

4

1 回答 1

0

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

这不是真的。

路径与您告诉<Link>组件的内容有关。例如,在/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,就像那样。<a>与标准锚 ( )的行为完全相同。应用于您的代码:

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

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

<Link to={`/${post.slug}`}>
   <Image>
</Link>
于 2021-01-14T18:21:32.070 回答