首页 > 解决方案 > 使用 gatsby-source-contentful 使用 Gatsbyjs 和 Contentful 渲染富文本

问题描述

我正在使用 gatsby-source-contentful v4.6.4

根据文档,我应该能够毫无问题地使用类似于以下的查询(来自文档的简化查询):

query MyQuery {
  contentfulBlogPost {
        id
        bodyRichText {
             raw
        }
    }
 }

连同 documentToReactComponents。但是,以下代码不会引发错误,只是不会解析富文本:

function ArticleBody({raw}) {

return (
<>
    {
        raw.map(rtNode => {
            return (
                <>
                    {documentToReactComponents(rtNode)}
                </>
            )
        })
    }
</>
);
}

export default ArticleBody;

标签: graphqlgatsbycontentful

解决方案


问题是我需要解析 JSON,并将对象降级到内容数组中。

这是组件:

function ArticleBody({raw}) {

return (
    <>
        {
            JSON.parse(raw).content.map(rtNode => {
                return (
                    <>
                        {documentToReactComponents(rtNode)}
                    </>
                )
            })
        }
    </>
);
}

export default ArticleBody;

这是 GraphQL 查询:

query{
          allContentfulBlog {
            edges {
              node {
                id
                blogPost {
                  raw
                }
              }
            }
          }
       }

推荐阅读