🎯 目标

构建一个支持多样文本内容展示的 RichTextView 组件,适用于:

  • 展示公告、协议、课程介绍、评论内容等富文本
  • 支持文字高亮、换行、超链接、图片嵌入
  • 支持 Markdown 简易语法解析(加粗、斜体、链接)
  • 可自定义样式、段落间距、点击跳转逻辑
  • 后续可拓展为可编辑富文本输入框

🧱 展示结构示意

欢迎使用 HarmonyOS!

点击查看[用户协议](https://example.com)或阅读 **使用指南**。

🖼 图片插入 ⟶ 示例图

🧰 组件实现:RichTextView.ets(简易 Markdown 语法解析器)

@Component
export struct RichTextView {
  @Prop content: string = ''
  @Prop fontSize: number = 14
  @Prop color: string = '#333'
  @Prop linkColor: string = '#007DFF'
  @Prop lineGap: number = 8

  build() {
    const lines = this.content.split('\n')

    Column({ space: this.lineGap }) {
      lines.forEach(line => {
        this.parseLine(line)
      })
    }
  }

  private parseLine(line: string) {
    // 简单规则:
    // [链接文字](url) → 链接
    // **加粗** → Bold
    // ![图片说明](图片地址) → 图片
    const regex = /(\*\*(.*?)\*\*)|(!\[(.*?)\]\((.*?)\))|(\[(.*?)\]\((.*?)\))/g
    const segments = []
    let lastIndex = 0
    let match

    while ((match = regex.exec(line)) !== null) {
      if (match.index > lastIndex) {
        segments.push({ type: 'text', value: line.slice(lastIndex, match.index) })
      }

      if (match[1]) {
        segments.push({ type: 'bold', value: match[2] })
      } else if (match[3]) {
        segments.push({ type: 'image', alt: match[4], src: match[5] })
      } else if (match[6]) {
        segments.push({ type: 'link', text: match[7], href: match[8] })
      }

      lastIndex = regex.lastIndex
    }

    if (lastIndex < line.length) {
      segments.push({ type: 'text', value: line.slice(lastIndex) })
    }

    Row({ space: 4 }).alignItems(VerticalAlign.Center).wrap() {
      segments.forEach(seg => {
        if (seg.type === 'text') {
          Text(seg.value).fontSize(this.fontSize).fontColor(this.color)
        } else if (seg.type === 'bold') {
          Text(seg.value).fontSize(this.fontSize).fontWeight(FontWeight.Bold).fontColor(this.color)
        } else if (seg.type === 'link') {
          Text(seg.text)
            .fontSize(this.fontSize)
            .fontColor(this.linkColor)
            .onClick(() => router.pushUrl(seg.href))
        } else if (seg.type === 'image') {
          Image(seg.src)
            .width(100)
            .height(60)
            .alt(seg.alt)
            .objectFit(ImageFit.Cover)
            .borderRadius(6)
        }
      })
    }
  }
}

📦 使用示例

@Entry
@Component
struct DemoRichText {
  build() {
    RichTextView({
      content: `欢迎使用 HarmonyOS!

点击查看[用户协议](https://example.com)或阅读 **使用指南**。

![示例图](https://example.com/demo.png)`,
      fontSize: 14
    })
  }
}

✨ 可扩展能力建议

功能说明
支持 Markdown 语法解析库替代正则解析,支持完整 Markdown 文档展示
插入表格 / 引用 / 代码块处理 > 引用、`表格`、代码 等语法
支持可复制、长按菜单实现长按文字段落 → 弹出复制/分享菜单
富文本编辑器版本(双向)扩展为可编辑组件,实现富文本写作、帖子发布等场景

📘 下一篇预告

第42篇:【HarmonyOS 5.0.0 或以上】构建通知弹窗组件 NotifyPopup:支持顶部弹出 / 多种样式 / 自动消失

更多推荐