前言
最近在开发一个taro项目中遇到一个问题, 需要在微信小程序中显示富文本编辑器的内容, 在考察了一些方案后, 最后选择使用wxParse作为最终方案,因为我的开发环境是使用了ts, 这篇文章主要记录在使用wxParse过程中遇到的问题及解决办法。
遇到的问题
首先如何继承wxParse到taro项目中?
其次如何在tsx中使用import template等标签?
解决办法
集成wxParse到taro项目中, 本身并不复杂,
- 按照官方文档,clone wxParse到本地,然后将wxParse文件夹复制到src目录下。
- 新建一个组件,用来封装wxParse,方便后续其他地方复用。
- 使用组件。
show me code
因为本地是ts环境, 稍微比js环境多些配置,用法稍微有变通的地方 - 修改本地tslint.json
"exclude": ["./src/wxParse"], - richTextParse组件代码
import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
// @ts-ignore
import WxParse from '../wxParse/wxParse'
export default class RichTextParse extends Component<RichTextParseProps, never> {
parseHtml() {
if (!this.$scope) {
return
}
const article = this.props.html || ''
WxParse.wxParse('article', 'html', article, this.$scope, 5)
}
render() {
this.parseHtml()
// @ts-ignore
const Import: any = <import src='../wxParse/wxParse.wxml' />
// @ts-ignore
const Template: any = <template is='wxParse' data='{{wxParseData:article.nodes}}'/>
return(
<View>
{Import}
{Template}
</View>
)
}
}
interface RichTextParseProps {
html: string
}
此处注意点,因为taro的View jsx没用定义import, template等属性, 导致如果直接使用ts会报错, 我这里的解决办法是在使用前先将类型声明为any类型,再引入。
