微信小程序 mp-html:专为小程序设计的富文本渲染组件

一、为什么选择 mp-html?

相比原生 rich-text 和其他富文本组件,mp-html 有三大核心优势:

  1. 兼容性极强:支持 HTML 标准标签(div、img、table、ul 等)和内联样式,能完美解析后端返回的复杂富文本数据,解决 rich-text 不支持的 video、audio 等标签问题。
  2. 功能全面:自带图片预览、链接跳转、长按复制、代码高亮等实用功能,无需额外开发。
  3. 灵活可控:支持通过配置禁用危险标签(如 script)、自定义样式隔离、动态更新内容,适配不同业务场景。

二、mp-html 快速上手:安装与配置

  1. 进入你的项目根目录

  2. Window+R→输入cmd→cd 你的项目根目录→在终端中执行初始化命令

    bash 复制代码
    npm init -y
  3. 通过 npm 安装 mp-html 组件
    在终端中继续执行安装命令(项目根目录下):

    bash 复制代码
    npm install mp-html --save
  4. 构建 npm(关键!小程序识别 npm 组件的必要步骤)

  • 微信开发者工具中 → 点击顶部「工具」→「构建 npm」;
  • 等待构建完成,构建成功后会在项目根目录生成 miniprogram_npm 文件夹,且其中包含 mp-html 组件(这是小程序实际使用的组件目录)。
  1. 组件引用路径(关键!避免路径错误)

    在要使用的页面json中配置组件路径:

    bash 复制代码
    "usingComponents": {"mp-html":"/miniprogram_npm/mp-html"}
  2. 在wxml中使用

    组件中就可以正常使用 mp-html 渲染富文本了,示例用法:

    bash 复制代码
    <mp-html content="{{html}}" />

三、核心用法:从基础渲染到高级配置

  1. 替换原生 rich-text

    xml 复制代码
    mp-html 的 content 属性仅支持完整 HTML 字符串,不支持模板内直接插值,需在 JS 中提前拼接
    <!-- content 属性接收拼接后的 HTML 字符串 -->
    <mp-html content="{{mpHtmlContent}}" />
    bash 复制代码
    // 组件内示例(Page 页面用法类似,在 onLoad 中调用)
    Component({
      properties: {
        questionItem: {
          type: Object,
          value: {},
          // 监听数据变化,动态更新 HTML
          observer: function(newVal) {
            this.updateMpHtmlContent(newVal);
          }
        }
      },
      data: {
        mpHtmlContent: "" // 存储拼接后的 HTML
      },
      methods: {
        updateMpHtmlContent(questionItem) {
          const { indexNum, questionContent } = questionItem;
          // 拼接 HTML(保留原样式,支持动态数据)
          const html = `
            <div style="overflow: auto; width: auto; word-wrap: break-word; font-size: 32rpx;">
              <span style="color: #1a73e8; font-weight: bold;">${indexNum}.</span>
              ${questionContent}
            </div>
          `;
          this.setData({ mpHtmlContent: html });
        }
      }
    });
  2. 样式优化:提取外部 CSS

    将内联样式提取到 WXSS,更易维护且支持复用:

    xml 复制代码
    /* 组件 WXSS */
    .question-container {
      overflow: auto;
      width: auto;
      word-wrap: break-word;
      font-size: 32rpx;
      line-height: 1.6;
      color: #333;
    }
    .question-index {
      color: #1a73e8;
      font-weight: bold;
      margin-right: 8rpx;
    }

    JS 拼接时引用类名:

    bash 复制代码
    updateMpHtmlContent(questionItem) {
      const { indexNum, questionContent } = questionItem;
      const html = `
        <div class="question-container">
          <span class="question-index">${indexNum}.</span>
          ${questionContent}
        </div>
      `;
      this.setData({ mpHtmlContent: html });
    }
  3. 特殊字符转义

    若富文本内容包含 <、>、& 等特殊字符,需先转义避免解析异常:

    bash 复制代码
    // 转义工具函数
    escapeHtml(str) {
      return str.replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;');
    },
    
    // 拼接时调用转义
    const escapedContent = this.escapeHtml(questionContent);
    const html = `<div class="question-container"><span class="question-index">${indexNum}.</span>${escapedContent}</div>`;
  4. 图片预览与配置

    mp-html 自带图片预览功能,无需额外开发,还可配置图片样式:

    bash 复制代码
    <!-- 配置图片最大宽度、加载失败占位图 -->
    <mp-html 
      content="{{mpHtmlContent}}"
      img-width="100%"
      img-placeholder="https://xxx.com/loading.png"
      bindtapimg="handleTapImg" <!-- 自定义图片点击事件 -->
    />
  5. 禁用危险标签

    bash 复制代码
    <mp-html 
      content="{{mpHtmlContent}}"
      disable-tags="script,iframe,object"
    />

四、实战场景:解决小程序富文本常见问题

场景 1:渲染带图片的题目内容

后端返回的题目内容包含 标签,rich-text 可能出现图片溢出,mp-html 可完美适配:

bash 复制代码
// 拼接包含图片的 HTML
const html = `
  <div class="question-container">
    <span class="question-index">${indexNum}.</span>
    ${questionContent} <!-- 包含 <img src="xxx.png" alt="题目图片"> -->
  </div>
`;

<mp-html content="{{mpHtmlContent}}" img-width="100%" mode="widthFix" />
相关推荐
Jinuss6 小时前
HTML页面http-equiv=“refresh“自动刷新原理详解
http·html
恩创软件开发8 小时前
创业日常2026-1-8
java·经验分享·微信小程序·小程序
沉默璇年14 小时前
如何通过python脚本下载高德离线底图瓦片并使用?
javascript·python·html
BianHuanShiZhe15 小时前
swift计算文本高度
前端·javascript·html
23级二本计科15 小时前
前端 HTML + CSS + JavaScript
前端·css·html
VekiSon16 小时前
综合项目实战——电子商城信息查询系统
linux·c语言·网络·http·html·tcp·sqlite3
腾讯云云开发16 小时前
微信发布AI小程序成长计划:免费云开发资源+1亿token额度!
微信小程序·ai编程·小程序·云开发
开发加微信:hedian11616 小时前
推客与分销场景下的系统架构实践:如何支撑高并发与复杂业务规则
小程序
用户514144480982416 小时前
section与article的区别与使用场景
html
程序员小李白16 小时前
定位.轮播图详细解析
前端·css·html