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

react-markdown v10无法渲染Base64图片,求推荐解决方案

在react-markdown v10.1.0中渲染Base64图片的解决方案

核心原因

react-markdown v10默认启用了rehype-sanitize插件,该插件会过滤掉data URI格式的图片资源,这就是你能看到alt文本但图片无法显示的根本原因。之前的方案失效是因为:

  • remark-images仅负责将Markdown图片语法转换为<img>标签,但无法绕过sanitize的过滤规则;
  • v8版本中rehypeRaw能生效是因为当时默认sanitize规则更宽松,而v10收紧了安全限制。

推荐实现步骤

1. 安装必要依赖

确保你已安装对应版本的依赖:

npm install react-markdown@10.1.0 rehype-sanitize hast-util-sanitize

2. 自定义sanitize规则允许Base64图片

通过扩展默认sanitize规则,添加对data:协议的支持:

import React from 'react';
import ReactMarkdown from 'react-markdown';
import rehypeSanitize from 'rehype-sanitize';
import { defaultSchema } from 'hast-util-sanitize';

// 扩展默认规则,允许img标签的src使用data URI
const customSanitizeSchema = {
  ...defaultSchema,
  attributes: {
    ...defaultSchema.attributes,
    img: [
      ...(defaultSchema.attributes.img || []),
      ['src', /^data:/]
    ]
  }
};

const MarkdownViewer = ({ markdownContent }) => {
  return (
    <ReactMarkdown
      rehypePlugins={[
        [rehypeSanitize, customSanitizeSchema]
      ]}
    >
      {markdownContent}
    </ReactMarkdown>
  );
};

export default MarkdownViewer;

3. 测试验证

使用你的测试Markdown内容(示例):

![测试Base64图片](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==)

此时图片应该能正常渲染。

替代方案(不推荐,仅作参考)

如果你能确保所有Markdown内容完全可信,可以直接禁用sanitize插件来简化配置,但这会带来XSS风险:

<ReactMarkdown rehypePlugins={[]}>
  {markdownContent}
</ReactMarkdown>

内容的提问来源于stack exchange,提问作者Anish K Pillai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 16:57:07