我正在尝试在博客文章上添加标签,但我很难找到解释如何实现它们的资源。
最终目标是获得可点击的标签,这会导致一个页面,其中所有具有相同标签的帖子都出现在一个列表中。
我将 GatsbyJS 与 Contentful 集成一起使用。
我有一个名为 article-post.tsx 的文件,其中包含以下代码:
import React from "react"
import { graphql } from "gatsby"
import { documentToReactComponents } from "@contentful/rich-text-react-renderer"
import Layout from "../components/layout/layout"
import Img from "gatsby-image"
import SEO from "../components/layout/seo"
import styled from "styled-components"
import { BodyMain, H1 } from "../components/styles/TextStyles"
export const query = graphql`
query($slug: String!) {
contentfulArticlePost(slug: { eq: $slug }) {
title
tags
publishedDate(formatString: "Do MMMM, YYYY")
featuredImage {
fluid(maxWidth: 720) {
...GatsbyContentfulFluid
}
}
body {
json
}
}
}
`
const ArticlePost = props => {
const options = {
renderNode: {
"embedded-asset-block": node => {
const alt = node.data.target.fields.title["en-US"]
const url = node.data.target.fields.file["en-US"].url
return <img alt={alt} src={url} className="embeddedImage" />
},
},
}
return (
<Layout>
<SEO title={props.data.contentfulArticlePost.title} />
<Wrapper>
<ImageWrapper>
{props.data.contentfulArticlePost.featuredImage && (
<Img
className="featured"
fluid={props.data.contentfulArticlePost.featuredImage.fluid}
alt={props.data.contentfulArticlePost.title}
/>
)}
</ImageWrapper>
<Title>{props.data.contentfulArticlePost.title}</Title>
<Tags>
{props.data.contentfulArticlePost.tags.map(tag => (
<span className="tag" key={tag}>
{tag}
</span>
))}
</Tags>
<ContentWrapper>
{documentToReactComponents(
props.data.contentfulArticlePost.body.json,
options
)}
</ContentWrapper>
</Wrapper>
</Layout>
)
}
export default ArticlePost
const Wrapper = styled.div`
display: grid;
grid-gap: 1.875rem;
margin: 0 auto;
padding: 7rem 1.875rem;
max-width: 900px;
`
const ImageWrapper = styled.div`
.featured {
border-radius: 15px;
}
`
const Title = styled(H1)`
margin: 0 auto;
text-align: center;
`
const Tags = styled.div`
margin: 0 auto;
.tag {
background: #8636E4;
border-radius: 1rem;
padding: 0.5rem;
margin: 0.2rem;
font-weight: 600;
}
`
const ContentWrapper = styled(BodyMain)`
display: grid;
grid-gap: 20px;
max-width: 900px;
margin: 0 auto;
line-height: 1.6;
.embeddedImage {
padding: 50px 0px;
width: 100%;
height: auto;
}
`
它确实给了我标签,我可以设计它们。虽然我不知道如何让它们像链接/按钮一样可点击。
我有一个名为 gatsby-node.js 的文件,其中包含以下代码:
const path = require("path")
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const response = await graphql(`
query {
allContentfulArticlePost {
edges {
node {
id
slug
}
}
}
}
`)
response.data.allContentfulArticlePost.edges.forEach(edge => {
createPage({
path: `/articles/${edge.node.slug}`,
component: path.resolve("./src/templates/article-post.tsx"),
context: {
slug: edge.node.slug,
id: edge.node.id
},
})
})
}
我从这里去哪里?