如何解决如何从富文本字段 Contentful 中获取内容
我正在一个测试项目中试用它。 这里来自 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
。
解决方法
像这样使用它:
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>
</>
)
},}
function BlogPostTemplate({ data }) {
const { bodyRichText } = data.contentfulBlogPost
return <div>{bodyRichText && renderRichText(richTextField,options)}</div>
}
最后,options
对象是一堆函数,它们根据您的项目逻辑返回自定义标记(即:<bold>{text}</bold>
当富文本具有粗体样式等时)所以,您只需要使用:
renderRichText(richTextField,options)
在您想要呈现内容的组件中,理想情况下,在模板中。
有关详细信息,请查看 plugin's docs。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。