问题描述
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">
→ Read this post
</ReadNavigate>
</div>
</BlogArticle>
);
};
export default TutorialPreview;
以上是我在主页上预览的模板,它适用于我的预览,在通过 Link 组件的行为列出所有帖子的页面的情况下,假定 slug 应该附加到当前页面堆栈。
例如
主页链接 = /{post.slug}
博客列表链接 = tutorials/{post.slug}
问题是帖子页面是使用页面级别的 slug 生成的,而不是嵌套在教程中。我试图避免使用到达路由器的 navigate()
方法,但存在这些页面的问题,直到您最初使用 Link 组件导航到它们。
我想知道是否有任何想法可以在不硬编码路径的情况下绕过这个问题,这样我就不需要单独的组件。
解决方法
链接组件假定 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>