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