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

在Strapi+Next.js博客中渲染富文本内iframe元素的方法咨询

解决Next.js + Strapi博客中Markdown无法渲染iframe的问题

我正在学习Strapi官方的《使用Next.js和Strapi搭建博客》教程,教程要求安装Markdown相关包:
安装Markdown相关包

包的使用位置如下:
包的使用位置

最终效果里iframe元素未渲染,需要通过MDX工具来实现,具体操作步骤如下:


1. 安装MDX相关依赖

先卸载原有的Markdown解析包(比如react-markdown),然后安装MDX支持工具:

npm install @mdx-js/react next-mdx-remote
# 或使用yarn
yarn add @mdx-js/react next-mdx-remote

2. 配置Next.js支持MDX(Pages Router)

在项目根目录的next.config.js中添加MDX配置:

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/,
})

module.exports = withMDX({
  pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'],
})

3. 在文章页面替换渲染逻辑

修改文章详情页(对应article/slug路径)的代码,用next-mdx-remote序列化并渲染内容:

import { serialize } from 'next-mdx-remote/serialize'
import { MDXRemote } from 'next-mdx-remote'

export async function getStaticProps({ params }) {
  // 从Strapi接口获取文章数据,content为包含iframe的MDX内容
  const articleRes = await fetch(`http://你的Strapi地址/api/articles/${params.slug}`)
  const article = await articleRes.json()

  // 序列化MDX内容
  const mdxSource = await serialize(article.data.attributes.content)

  return {
    props: {
      article: {
        ...article.data.attributes,
        mdxSource,
      },
    },
  }
}

export default function ArticlePage({ article }) {
  return (
    <div className="article-container">
      <h1>{article.title}</h1>
      {/* 渲染MDX内容,自动解析iframe */}
      <MDXRemote {...article.mdxSource} />
    </div>
  )
}

4. 自定义iframe样式(可选)

如果需要统一设置iframe的样式,可以自定义MDX组件:

// 定义自定义组件
const CustomComponents = {
  iframe: (props) => (
    <iframe
      {...props}
      style={{ width: '100%', height: '500px', borderRadius: '8px', border: 'none' }}
      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
      allowFullScreen
    />
  ),
}

// 在MDXRemote中传入自定义组件
<MDXRemote {...article.mdxSource} components={CustomComponents} />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:45:23