react-native中react-native-render-html的使用(不崩溃)

1、react-native-render-html和react-native-htmlview的比较

App项目中需要用到解析HTML的组件,在github上面找到比较合适的两款,react-native-render-html(RNRH)和react-native-htmlview(RNH)。子啊实际的使用过程中,两个各自有不同的问题。

首先RNRH容易红屏,这个使用过的人肯定有体会,而RNH则在图片方面比较不好处理,最终我选择了RNRH。

2、使用

安装什么的就不说了

import HTML from "react-native-render-html";

然后在组件的render中

<HTML
     ignoredStyles={["font-family", "transform", "display", "border-style", "max-width", "default-src", "loadingIndicatorSrc"]}
     renderers={renderer}
     debug={true}
     tagsStyles={{p: {fontSize: 16}, span: {fontSize: 16}}}
     html={this.state.htmlContent}
     imagesMaxWidth={width}/>

注意组件的ignoredStyles属性,这里配置的是需要忽略的css属性,很多导致崩溃的原因就是有些css属性无法解析。所以使用过程中,查看日志很重要,哪个属性导致的崩溃,可以添加在这里。

renderers的写法如下,主要处理图片

const width = Dimensions.get('window').width;
const renderer = {
	img: (htmlAttribs, children, convertedCSSStyles, passProps) => {
		const wid = htmlAttribs.width ? htmlAttribs.width : width;
		const hei = htmlAttribs.height ? htmlAttribs.height * (width - 20) / wid : 200;
		console.log(htmlAttribs.src);
		imageArr.push({index: i, uri: htmlAttribs.src});//将图片放入overlay中点击查看
		this.setState({
			images: imageArr
		});
		i++;
		return (
			<TouchableNativeFeedback
				key={i}
				onPress={() => {
					let index = 0;
					this.state.images.map((item) => {
						if (item.uri === htmlAttribs.src) {
							index = item.index;
						}
					});
					this.setState({
						overLayVisible: true,
						overLayImageIndex: index
					});
				}}>
				<Image
					key={htmlAttribs.src}
					style={{height: hei, width: width - 20}}
					resizeMode='contain'
					source={{uri: htmlAttribs.src}}/>
			</TouchableNativeFeedback>
		)
	},
	ul: (htmlAttribs, children, passProps) => {
		return <Text style={{
			fontWeight: 'normal',
			marginLeft: 10,
			paddingLeft: 0,
			color: '#333',
			fontSize: 14,
			fontFamily: 'roboto_slab'
		}} {...passProps}>{children}</Text>
	},
};

采用这种方式可以保持图片原来的长宽比,不是导致图片失真或者变形。

另外我的后台文本编辑器为百度的Ueditor,两者配合基本满分。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章