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

在App项目中,对比了react-native-render-html(RNRH)和react-native-htmlview(RNH),发现RNRH易红屏,而RNH图片处理不佳。最终选择RNRH并解决其崩溃问题。通过设置ignoredStyles忽略导致崩溃的CSS属性,并使用特定renderers处理图片以保持长宽比,确保与后台Ueditor配合良好。
部署运行你感兴趣的模型镜像

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,两者配合基本满分。

您可能感兴趣的与本文相关的镜像

Langchain-Chatchat

Langchain-Chatchat

AI应用
Langchain

Langchain-Chatchat 是一个基于 ChatGLM 等大语言模型和 Langchain 应用框架实现的开源项目,旨在构建一个可以离线部署的本地知识库问答系统。它通过检索增强生成 (RAG) 的方法,让用户能够以自然语言与本地文件、数据库或搜索引擎进行交互,并支持多种大模型和向量数据库的集成,以及提供 WebUI 和 API 服务

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值