在微信小程序下会用到wxParse这个东西来达到html转换wxml的效果,
taro小程序官方也给出了示例,地址
这里封装成自己的组件:
1import Taro, { Component } from "@tarojs/taro" 2import { View } from "@tarojs/components" 3import WxParse from '../../utils/wxParse/wxParse.js' 4import "../../utils/wxParse/wxParse.scss" 5 6export default class ParseComponent extends Component { 7 componentDidMount() {} 8 defaultProps = { 9 mark: "" 10 } 11 render() { 12 13 if (this.props.mark) { 14 let domText = this.props.mark 15 WxParse.wxParse("domText", "html", domText, this.$scope, 5); 16 } 17 return ( 18 <View> 19 {process.env.TARO_ENV === "weapp" ? ( 20 <View> 21 <import src='../../utils/wxParse/wxParse.wxml' /> 22 <template is='wxParse' data='{{wxParseData:domText.nodes}}' 23 /> 24 </View> 25 ) : ( 26 <View>只在小程序里支持</View> 27 )} 28 </View> 29 ); 30 } 31}
另外,转化之后的图片地址是相对地址,在小程序中是无法显示的,所以需要到html2json.js文件中加上图片的域名地址:
1//对img添加额外数据 2 if (node.tag === 'img') { 3 node.imgIndex = results.images.length; 4 var imgUrl = '域名地址' + node.attr.src; 5 if (imgUrl[0] == '') { 6 imgUrl.splice(0, 1); 7 } 8 imgUrl = wxDiscode.urlToHttpUrl(imgUrl, __placeImgeUrlHttps); 9 node.attr.src = imgUrl; 10 node.from = bindName; 11 results.images.push(node); 12 results.imageUrls.push(imgUrl); 13 }