微信小程序 rich-text 元件詳解
當我們需要在小程序中渲染一段 HTML 字串時,rich-text 就是官方提供的解決方案。以下整理它的屬性規則與使用方式。
nodes,類型為 Array 或 String,代表節點列表或 HTML String。class 與 style 屬性,但不支援 id。type = node:name 為標籤名(String,必填),支援部分受信任的 HTML 節點;attrs 為屬性(Object,可選),支援部分受信任的屬性並遵循 Pascal 命名法;children 為子節點列表(Array,可選),結構與 nodes 一致。type = text:text 為文字內容(String,必填),支援 entities。nodes 使用 String 類型,效能會有所下降。attrs 不支援 id,但支援 class。name 屬性大小寫不敏感。img 標籤僅支援網路圖片。 <rich-text nodes="{{nodes}}" /> <rich-text nodes="{{nodes1}}" /> <rich-text nodes="{{nodes2}}" />

下面示範三種不同的傳入方式:直接給 HTML 字串、給單層節點物件、以及給多層嵌套的節點結構。
this.setData({ nodes: "<h1 style='color:red;'>html標題</h1>", nodes1: [{ name: "h1", attrs: { style: "color:red", class: "red" }, children: [{ type: "text", text: '結點列表標題' }] }], nodes2: [{ name: "ul", attrs: { style: "padding:20px;border:1px solid blue;", class: "red" }, children: [ { name: "li", attrs: { style: "color:red", class: "red" }, children: [{ type: "text", text: '多層結點 無序列表' }], }, { name: "li", attrs: { style: "color:red", class: "red" }, children: [{ type: "text", text: '多層結點 無序列表1' }], }] }] })
如果資料來源本身就是 HTML 字串(例如後端回傳的富文本內容),用 String 形式最省事;若資料是自己在程式中組出來的,建議直接用 Array 節點結構,效能表現更好,也更便於動態增減節點。要注意的是,因為元件內事件被屏蔽,若需要點擊互動,得在外層另外想辦法處理。
以上就是 rich-text 的介紹,有疑問歡迎留言或到社群交流討論。