首页 > 编程笔记 > 通用技能 阅读:1

ArkTS RichText组件的用法(附带实例)

RichText 是富文本组件,用于解析并显示 HTML 格式文本。该组件适用于加载与显示一段 HTML 字符串,且不需要对显示效果进行较多自定义的应用场景。

由于 RichText 组件底层复用了 Web 组件来提供基础能力,包括但不限于 HTML 页面的解析、渲染等,所以使用 RichText 组件需要遵循 Web 约束条件。

RichText 组件不适用于对 HTML 字符串的显示效果进行较多自定义的应用场景。例如 RichText 组件不支持通过设置属性与事件来修改背景颜色、字体颜色、字体大小和动态改变内容等。在这种情况下,推荐使用 Web 组件。

需要注意的是,RichText 组件比较消耗内存资源,而且在一些重复使用 RichText 组件的场景下,比如在 List 下循环使用 RichText,会出现卡顿、滑动响应慢等现象。

RichText 组件的示例代码如下:
// 引入路由模块,用于页面跳转传参
import { router } from '@kit.ArkUI';
// 引入自定义导航栏组件(起别名 MyNavbar)
import { Navbar as MyNavbar } from '../components/navBar';

@Entry
@Component
struct RichTextCom {
  // 接收页面跳转时传递的描述与标题
  @State desc: string = '';     // 组件描述
  @State title: string = '';    // 页面标题

  // 富文本内容:支持 HTML 标签与内联样式
  @State data: string =
    '<h1 style="text-align: center;">h1标题</h1>' +
    '<h1 style="text-align: center;"><i>h1斜体</i></h1>' +
    '<h1 style="text-align: center;"><u>h1下画线</u></h1>' +
    '<h2 style="text-align: center;">h2标题</h2>' +
    '<h3 style="text-align: center;">h3标题</h3>' +
    '<p style="text-align: center;">p常规</p><hr/>' +
    '<div style="width: 500px; height: 500px; border: 1px solid; margin: 0 auto;">' +
      '<p style="font-size: 35px; text-align: center; font-weight: bold; color: rgb(24,78,228);">字体大小35px,行高45px</p>' +
      '<p style="background-color: #e5e5e5; line-height: 45px; font-size: 35px; text-indent: 2em;">' +
        '这是一段文字这是一段文字这是一段文字这是一段文字这是一段文字' +
      '</p>' +
    '</div>';

  // 页面显示时触发:解析路由参数
  onPageShow(): void {
    // 获取跳转时携带的参数对象
    const params = router.getParams() as Record<string, string>;
    if (params) {
      this.desc = params.desc  as string;   // 组件描述
      this.title = params.value as string;  // 页面标题
    }
  }

  build() {
    Column() {
      // 自定义导航栏,传入标题
      MyNavbar({ title: this.title })

      // 黑色分割线
      Divider()
        .width('100%')
        .strokeWidth(2)
        .color(Color.Black)

      // 组件描述行
      Row() {
        Text(`组件描述:${this.desc}`)
      }

      // 灰色分割线
      Divider()
        .width('100%')
        .strokeWidth(5)
        .color('#e5e5e5')

      // 富文本组件
      RichText(this.data)
        .onStart(() => {
          console.info('RichText onStart');
        })
        .onComplete(() => {
          console.info('RichText onComplete');
        })
        .width(500)
        .height(500)
        .backgroundColor(0xBDDB69)
    }
    .width('100%')
    .height('100%')
  }
}
RichText 组件的示例效果如下图所示:


图 1 RichText组件的示例效果

相关文章