介绍
本示例通过自定义Span类型,在Text组件中使用ForEach遍历,根据不同的Span类型生成不同样式和功能的Span组件,实现部分文本高亮和超链接。
效果图预览
使用说明
1.点击超链接,根据链接类型出现相应提示弹窗。
2.长按消息卡片出现提示弹窗。
实现思路
1.定义 CustomSpanType 枚举类型,此处定义了 Normal、Hashtag、Mention、VideoLink 和 DetailLink 五种类型。
export enum CustomSpanType {
Normal, // 普通文本,不含任何特殊格式或标记
Hashtag, // 话题标签
Mention, // @提及
VideoLink, // 视频链接
DetailLink // 正文详情
}
2.创建 CustomSpan 数据类,用于表示不同类型的 Span 对象。
export class CustomSpan {
type: CustomSpanType; // 文本类型
content: string; // 文本内容
url?: string; // 跳转的链接地址
constructor(type: CustomSpanType = CustomSpanType.Normal, content: string, url?: string) {
this.type = type;
this.content = content;
if (url) {
this.url = url;
}
}
}
3.使用 Text 组件结合 ForEach 方法遍历 spans 中的 CustomSpan 对象,根据不同的 Span 类型生成不同样式和功能的 Span 组件。
Text() {
ForEach(this.spans, (item: CustomSpan) => {
if (item.type === CustomSpanType.Normal) {
Span(item.content)
.fontSize($r('app.string.ohos_id_text_size_body1'))
} else if (item.type === CustomSpanType.Hashtag || item.type === CustomSpanType.Mention || it