React Native使用react-native-render-html渲染数组HTML时显示空白的问题咨询
问题排查与修正方案
第一步:修正核心拼写错误
当前代码中给react-native-render-html组件传入HTML源内容的属性名存在拼写偏差,组件无法读取到正确的HTML字符串,直接导致渲染结果为空白:
- 错误写法:
<HTML souce={{ html: testArray[0].freeText }} /> - 正确写法:
<HTML source={{ html: testArray[0].freeText }} />
注:当前版本的
react-native-render-html接收HTML内容的固定属性名是source,拼写不匹配会导致组件完全获取不到渲染源。
版本适配提示:如果使用的是2021年之前发布的旧版本库,接收HTML的属性是直接的html而非嵌套的source结构,可以根据安装的库版本匹配对应写法。
第二步:补充文本样式避免视觉异常
你在外层容器上写的color: "black"属性在React Native的View组件上不生效,View组件本身不会向下继承文本颜色,部分安卓机型上如果渲染的HTML文本没有显式指定颜色,会出现文本和背景同色的视觉效果,看起来就像完全没渲染内容。可以通过tagsStyles属性给标签指定默认文本颜色:
<HTML source={{ html: testArray[0].freeText }} contentWidth={contentWidth} tagsStyles={{ p: { color: 'black' }, strong: { color: 'black' } }} />
第三步:环境校验避免依赖异常
如果修正拼写和样式后依然空白,按以下步骤排查:
- 确认
react-native-render-html的版本与当前项目的React Native版本适配,完整安装库的配套peer依赖 - 清除Metro缓存重启项目,避免旧的打包缓存导致组件无法正常加载,执行命令:
npx react-native start --reset-cache
修正后完整可运行代码
import React from "react"; import { View, StyleSheet, useWindowDimensions, } from "react-native"; import HTML from "react-native-render-html"; const BannerWidget = () => { const contentWidth = useWindowDimensions().width; const testArray = [ { productType: "Package", status: "Included", productName: "Advanced", IsFreeProductRedeemed: false, PackageItems: ["xxx", "ccc"], freeText: "<p>sample <strong> FREE </strong> </p>", }, ]; return ( <View style={styles.container}> <HTML source={{ html: testArray[0].freeText }} contentWidth={contentWidth} tagsStyles={{ p: { color: 'black' } }} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 10, }, }); export default BannerWidget;
内容的提问来源于stack exchange,提问作者Bomber
相关产品推荐
相关产品推荐

