【发布时间】:2021-06-19 09:26:39
【问题描述】:
我正在一个测试项目中尝试它。 这里来自 Index.js
const IndexPage = ({data: {posts}}) => {
return (
<div>
<h1>Test Page</h1>
{posts.edges.map(({node}) => (
<Card key={node.id} node={node} />
))}
</div>
)
}
export default IndexPage;
export const query = graphql`
query {
posts: allContentfulPost {
edges {
node {
id
title
slug
content{
content
}
body{
raw
}
}
}
}
}
`
我已将您建议的代码复制到我的模板组件 card.js 中。这是我尝试渲染富文本字段的时候。
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>
let richTextField;
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>
</>
)
},
},
}
function Card({ node }) {
const { body } = node.body
return (
<article style={{backgroundColor:"red"}}>
{/* <Img fluid={images[0].FluidObject} alt=""/> */}
{/* <a href={`/posts/${node.slug}`}>
<h2>{node.title}</h2>
</a>
<p>
{node.content.content}
</p> */}
<div>{body && renderRichText(richTextField, options)}</div>
</article>
)
}
export default Card;
但它不会渲染出richTextField。首先它抱怨richTextField 未定义,所以我在文件开头添加了let richTextField。
【问题讨论】:
-
你自己的组件是什么样的?您是否检查过上一个答案中链接的
gatsby-source-contentfulplugin docs 中的示例? -
iv'e 更新了我的问题@JulioMalves
标签: gatsby contentful richtext