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

Gatsby调用renderRichText渲染Contentful富文本出现空白页问题求助

问题根因

  • 字段名不匹配:GraphQL查询返回的富文本字段为body,但组件中错误解构了不存在的bodyRichText字段,导致渲染条件始终不触发,页面空白。
  • 富文本标记渲染逻辑不全:当前粗体标记的渲染规则仅用普通span包裹文本,无粗体样式,无法还原后台配置的格式。

修复后完整代码

/* eslint-disable */
import React from 'react';
import { Helmet } from 'react-helmet';
import { graphql } from 'gatsby';
import Layout from '../components/layout';
import { renderRichText } from "gatsby-source-contentful/rich-text"
import { BLOCKS, MARKS } from "@contentful/rich-text-types"

export const query = graphql`
query MyQuery($slug: String) {
    contentfulLongPost(Slug: {eq: $slug}) {
      title
      updatedAt(formatString: "MMMM Do, YYYY")
      body {
        raw
        # 如果有嵌入的图片/资源,需要额外查询references字段
        references {
          ... on ContentfulAsset {
            contentful_id
            __typename
            gatsbyImageData
          }
        }
      }
    }
  }
`;

const options = {
  renderMark: {
    // 还原粗体格式,直接用strong标签或自定义带样式的元素
    [MARKS.BOLD]: (text) => <strong style={{fontWeight: 700}}>{text}</strong>,
    // 可按需添加斜体、下划线等其他标记的渲染规则
    [MARKS.ITALIC]: (text) => <em>{text}</em>,
  },
  renderBlock: {
    // 还原段落、标题等块级元素格式
    [BLOCKS.PARAGRAPH]: (node, children) => <p style={{margin: '12px 0'}}>{children}</p>,
    [BLOCKS.HEADING_1]: (node, children) => <h1>{children}</h1>,
    [BLOCKS.HEADING_2]: (node, children) => <h2>{children}</h2>,
    // 嵌入图片的渲染示例(需要配合上面查询的references字段)
    [BLOCKS.EMBEDDED_ASSET]: (node) => {
      const { gatsbyImageData } = node.data.target
      return <img src={gatsbyImageData.images.fallback.src} alt="" style={{maxWidth: '100%'}} />
    }
  }
}

const CaseStudy = ({data}) => {
    // 修正字段名,取查询返回的body字段
    const { body } = data.contentfulLongPost
    return (
        <Layout>
        <div>{body && renderRichText(body, options)}</div>
        </Layout>
    );
};

export default CaseStudy;

补充说明

如果需要完整还原所有富文本格式,只需要在options的renderMark和renderBlock中对应配置MARKS、BLOCKS枚举下的类型即可,所有枚举值可参考@contentful/rich-text-types包的定义。

内容的提问来源于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 07:36:04