问题描述
嘿,我正在使用 gatsby srouce contentful 从 contenful 获取我的博客文章。我正在尝试将正文作为富文本或 json 格式获取,但 graphql 可以让我使用的唯一选项是 raw,它会返回一堆对象和我不想要的文本。
解决方法
步骤 1. 确保您已使用以下方法导入 gatsby-source-contentful:
npm install gatsby-source-contentful
第 2 步。将此添加到您的导入中:
import { renderRichText } from "gatsby-source-contentful/rich-text"
第 3 步。您的查询应如下所示
export const query = graphql`
query($slug: String!){
contentfulBlogPost(slug: {eq: $slug}) {
title
publishedDate(formatString: "MMMM Do,YYYY")
body{
raw
}
}
}`
步骤 4. return {renderRichText(props.data.contentfulBlogPost.body)}
const Blog = (props) => {
return(
<Layout>
<h1>{props.data.contentfulBlogPost.title}</h1>
<p>{props.data.contentfulBlogPost.publishedDate}</p>
<div>{renderRichText(props.data.contentfulBlogPost.body)}</div>
</Layout>
)
}
我希望这会有所帮助,这是我关于堆栈溢出的第一个答案,我相信根据您提出问题的方式,我们正在关注同一个训练营。
https://www.youtube.com/watch?v=8t0vNu2fCCM&t=590s&ab_channel=AndrewMead
如果你想合作和互相学习,给我留言。
这也可能有帮助:https://www.gatsbyjs.com/plugins/gatsby-source-contentful/#query-rich-text-content-and-references
添加另一个解决方案:
export const query = graphql`
query($slug: String!){
contentfulBlogPost(slug: {eq: $slug}) {
title
publishedDate(formatString: "MMMM Do,YYYY")
body{
raw
references {
fixed(width: 750) {
width
height
src
}
}
}
}
}
`
添加对原始数据的引用。
const Blog = (props) => {
const options = {
renderNode: {
"embedded-asset-block": (node) => {
const alt = "test"
const url = props.data.contentfulBlogPost.body.references[0].fixed.src
return <img src={url} alt={alt}/>
}
}
}
最后在渲染部分:
<div>{renderRichText(props.data.contentfulBlogPost.body,options)}</div>
,
raw
对象是最新版本的 gatsby-source-contentful
中添加的新“功能”。根据{{3}}:
注意:请注意,以前版本的 Gatsby Contentful 源插件使用了 json
字段。这被替换为 raw
给
您可以更灵活地进行渲染和修复性能问题。
Contentful 指出的“灵活性”是自定义组件的 return
语句的输出的能力,该语句将解析 raw
响应。理想情况下,您应该具有以下内容:
import { BLOCKS,MARKS } from "@contentful/rich-text-types"
import { renderRichText } from "gatsby-source-contentful/rich-text"
const Bold = ({ children }) => <span className="bold">{children}</span>
const Text = ({ children }) => <p className="align-center">{children}</p>
const options = {
renderMark: {
[MARKS.BOLD]: text => <Bold>{text}</Bold>,},renderNode: {
[BLOCKS.PARAGRAPH]: (node,children) => <Text>{children}</Text>,[BLOCKS.EMBEDDED_ASSET]: node => {
return (
<>
<h2>Embedded Asset</h2>
<pre>
<code>{JSON.stringify(node,null,2)}</code>
</pre>
</>
)
},}
renderRichText(node.bodyRichText,options)
上面的代码段允许您为每个 MARKS
和 BLOCKS
条目自定义响应,如果需要添加适当的样式并将其包装在您可能需要的任何结构中。上面的组件将允许您解析原始响应并返回正确的组件。
您可以查看此答案和 docs 中提供的 Contentful 文档以获取更多详细信息。