【发布时间】:2021-03-23 12:51:07
【问题描述】:
我正在尝试从 Contentful 获取富文本,但在 gatsby-source-contentful 的 4.x 版本中,文档似乎不再更新。引用的是json,但是改成了raw,不知道怎么处理。
这是我的代码:
import React from "react"
import { graphql, Link } 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"
export const query = graphql`
query($slug: String!) {
contentfulBlogPost(slug: { eq: $slug }) {
title
publishedDate(formatString: "Do MMMM, YYYY")
featuredImage {
fluid(maxWidth: 750) {
...GatsbyContentfulFluid
}
}
body {
json
}
}
}
`
const BlogPost = 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} />
},
},
}
return (
<Layout>
<SEO title={props.data.contentfulBlogPost.title} />
<Link to="/blog/">Visit the Blog Page</Link>
<div className="content">
...
{props.data.contentfulBlogPost.featuredImage && (
<Img
className="featured"
fluid={props.data.contentfulBlogPost.featuredImage.fluid}
alt={props.data.contentfulBlogPost.title}
/>
)}
{documentToReactComponents(
props.data.contentfulBlogPost.body.json,
options
)}
</div>
</Layout>
)
}
export default BlogPost
如果您查看下面的部分,我相信这就是错误的地方。我收到的错误消息是“无法在类型“ContentfulBlogPostBody”上查询字段“json”。”,但如果我将其更改为 raw 而不是 json,它不会给我任何错误,但它不会显示富文本(正文):
}
body {
json
}
}
}
`
以下是 Contentful 中如何设置内容模型的屏幕截图:
如何使用较新版本的 gatsby-source-contentful(目前为 4.2.1 版)并改变它处理富文本的方式?
【问题讨论】:
标签: reactjs gatsby contentful