You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Contentful富文本raw字段不渲染 GraphQL查询无法获取内容问题

问题排查与解决方案

你精简查询仅请求raw字段就返回空数组,和references下__typename后追加的字段无关,先按以下步骤排查:

  • 先打开Gatsby内置的GraphiQL调试工具(默认地址http://localhost:8000/___graphql),手动传入存在的slug固定值执行你的精简测试语句,确认对应内容在Contentful后台的富文本字段是否确实已填充、模型字段名是否和查询的body一致、contentfulLongPost模型匹配规则是否正确。如果GraphiQL里查询raw有值,就是你页面的slug参数传递错误;如果GraphiQL里也为空,直接检查Contentful后台的内容配置。

如果确认raw字段能正常返回后,如果你需要渲染富文本中的图片等资源,才需要在__typename后追加你需要用到的资源字段,示例如下:

query MyQuery($slug: String) {
    contentfulLongPost(Slug: { eq: $slug }) {
        title
        updatedAt(formatString: "MMMM Do, YYYY")
        body {
            raw
            references {
                ... on ContentfulAsset {
                    contentful_id
                    __typename
                    # 下方是渲染资源需要的字段,按需添加即可
                    title
                    description
                    gatsbyImageData(layout: CONSTRAINED, width: 1200)
                    file {
                        url
                    }
                }
            }
        }
        free
        contentType
    }
}

自定义富文本CSS的实现方法

你用的documentToReactComponents支持传入自定义渲染选项,给不同富文本节点指定带自定义类名的组件,示例代码如下:

const caseStudy = (props) => {
    const richText = props.data.contentfulLongPost.body;
    // 自定义渲染规则
    const options = {
        renderNode: {
            // 自定义h1标签样式
            'heading-1': (node, children) => <h1 className="text-3xl font-bold mb-4">{children}</h1>,
            // 自定义段落样式
            'paragraph': (node, children) => <p className="mb-3 leading-relaxed">{children}</p>,
            // 自定义图片渲染
            'embedded-asset-block': (node) => {
                const asset = richText.references.find(ref => ref.contentful_id === node.data.target.sys.id);
                return <img src={asset.file.url} alt={asset.description} className="rounded-lg my-6 w-full" />
            }
        }
    }

    return (
        <Layout>
            <h1>{props.data.contentfulLongPost.title}</h1>
            <div className="rich-text-container">
                {documentToReactComponents(JSON.parse(richText.raw), options)}
            </div>
        </Layout>
    );
};

内容的提问来源于stack exchange,提问作者Shuib Abdillahi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 06:57:00