在微信小程序下會用到wxParse這個東西來達到html轉換wxml的效果,
taro小程序官方也給出了示例,地址
這里封裝成自己的組件:
import Taro, { Component } from "@tarojs/taro"
import { View } from "@tarojs/components"
import WxParse from '../../utils/wxParse/wxParse.js'
import "../../utils/wxParse/wxParse.scss"
export default class ParseComponent extends Component {
componentDidMount() {}
defaultProps = {
mark: ""
}
render() {
if (this.props.mark) {
let domText = this.props.mark
WxParse.wxParse("domText", "html", domText, this.$scope, 5);
}
return (
<View>
{process.env.TARO_ENV === "weapp" ? (
<View>
<import src='../../utils/wxParse/wxParse.wxml' />
<template is='wxParse' data='{{wxParseData:domText.nodes}}'
/>
</View>
) : (
<View>只在小程序里支持</View>
)}
</View>
);
}
}
另外,轉化之后的圖片地址是相對地址,在小程序中是無法顯示的,所以需要到html2json.js文件中加上圖片的域名地址:
//對img添加額外數據 if (node.tag === 'img') { node.imgIndex = results.images.length; var imgUrl = '域名地址' + node.attr.src; if (imgUrl[0] == '') { imgUrl.splice(0, 1); } imgUrl = wxDiscode.urlToHttpUrl(imgUrl, __placeImgeUrlHttps); node.attr.src = imgUrl; node.from = bindName; results.images.push(node); results.imageUrls.push(imgUrl); }
