官方:https://developers.weixin.qq.com/miniprogram/dev/component/rich-text.html
微信小程序的rich-text组件用来展示富文本内容。它的nodes属性可以用来设置富文本内容,nodes的类型是Array,数组中的每一项是一个节点。
解决方案1:直接在wxml文件中使用rich-text组件
<rich-text nodes="{{htmlContent}}"></rich-text>
在js文件中设置htmlContent的值:
Page({
data: {
htmlContent: '<div>Hello World!</div>'
}
})
解决方案2:使用数组的方式来设置nodes的值
<rich-text nodes="{{nodes}}"></rich-text>
在js文件中设置nodes的值:
Page({
data: {
nodes: [
{
name: 'div',
attrs: {
class: 'class-name',
style: 'color: red;'
},
children: [{
type: 'text',
text: 'Hello World!'
}]
}
]
}
})
解决方案3:使用wxParse库来解析html
首先,你需要在项目中安装wxParse库,可以在微信小程序wxParse的GitHub仓库中下载。
然后,在你的项目中的对应位置进行引入并使用:
<import src="../../wxParse/wxParse.wxml"/>
<template is="wxParse" data="{{wxParseData:article.nodes}}"/>
在js文件中:
var WxParse = require('../../wxParse/wxParse.js');
Page({
data: {
article: ''
},
onLoad: function () {
var that = this;
wx.request({
url: '你的html内容地址',
headers: {
'Content-Type': 'text/html; charset=utf-8'
},
success: function(res) {
that.data.article = WxParse.wxParse('article', 'html', res.data, that, 5);
that.setData({
article: that.data.article
});
}
});
}
})
以上就是在微信小程序中使用rich-text组件的几种方法。