Gatsby 如何从富文本字段Contentful获取内容

Gatsby 如何从富文本字段Contentful获取内容,gatsby,contentful,richtext,Gatsby,Contentful,Richtext,我正在一个测试项目中尝试。 以下是Index.js中的 const IndexPage = ({data: {posts}}) => { return ( <div> <h1>Test Page</h1> {posts.edges.map(({node}) => ( <Card key={node.id} node={node} /> ))} </div>

我正在一个测试项目中尝试。 以下是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
         }
      }
    }
  }
}
`
) }, }, } 功能卡({node}){ const{body}=node.body 返回( {node.content.content}

*/} {body&&renderRichText(richTextField,options)} ) } 导出默认卡; 但它不会渲染richTextField。首先,它抱怨richTextField没有定义,所以我在文件的开头添加了
让richTextField

这样使用它:

renderRichText(richTextField, options)
) }, }, } 函数BlogPostTemplate({data}){ const{bodyRichText}=data.contentfulBlogPost 返回{bodyRichText&&renderRichText(richTextField,options)} } 最后,
选项
对象是一组函数,它们根据您的项目逻辑返回自定义标记(即:
{text}
当富格文本具有粗体样式时,等等),因此,您只需要使用以下方法渲染它:

在您希望呈现内容的组件中,理想情况下是在模板中


有关更多详细信息,请查看。

您自己的组件是什么样子的?您是否检查了上一个答案中链接的示例?iv'e更新了我的问题@JulioMalvesSee我的更新问题@ferranbuireu
选项在哪里?在打印之前,您需要将查询到的数据传递到options对象中。这就是我感到困惑的地方。我是否应该用查询的数据替换
子项
文本
?在哪里使用
const Bold
const Text
。我需要一个指南,告诉我这个代码的每个部分都有什么作用^ ^@Ferranbuireouoh我现在明白了,是的,
选项
就在
功能卡
之前。没有显示它,因为它抱怨我的问题中有太多的代码。将它放在渲染时需要解析内容的组件(函数)中。您只需要在每种类型的内容中返回您想要的内容:
[MARKS.BOLD]:text=>{text},
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>
}
renderRichText(richTextField, options)