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

如何通过allMdx查询结合gatsby-plugin-mdx渲染MDX内容?

实现Gatsby从allMdx渲染MDX文章列表(替代MDXRenderer)

完全可行,针对gatsby-plugin-mdx移除MDXRenderer的情况,你可以通过查询编译后的MDX渲染函数来实现文章列表渲染,具体步骤如下:

1. 修改GraphQL查询字段

不再查询body原始MDX内容,改用compiledMdx.render字段,该字段返回已编译好的React组件渲染函数:

export const query = graphql`
  query MyQuery {
    allMdx {
      nodes {
        id
        compiledMdx {
          render
        }
        frontmatter {
          title
          slug
        }
      }
    }
  }
`;

2. 遍历节点渲染MDX内容

在组件中,将每个节点的compiledMdx.render作为React组件直接调用,即可渲染MDX内容:

export default function BlogList({ data }) {
  return (
    <div className="blog-list">
      {data.allMdx.nodes.map((node) => {
        const MDXContent = node.compiledMdx.render;
        return (
          <article key={node.id} className="blog-post">
            <h2>{node.frontmatter.title}</h2>
            {/* 渲染编译后的MDX内容 */}
            <MDXContent />
          </article>
        );
      })}
    </div>
  );
}

3. 自定义MDX组件(可选)

如果需要给MDX内容添加容器或自定义组件,可将自定义组件作为props传给MDXContent:

// 自定义包裹组件
function MDXWrapper({ children }) {
  return <div className="prose max-w-none">{children}</div>;
}

// 在渲染时传入组件
<MDXContent components={{ wrapper: MDXWrapper }} />

也可以在gatsby-config.js的gatsby-plugin-mdx配置中全局注册自定义组件,避免每次渲染都传入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:25:19