美文网首页
React Native HTMLView

React Native HTMLView

作者: 楚丶liu香 | 来源:发表于2020-09-10 19:36 被阅读0次

    最近在开发React Native功能模块时,服务端下发了一个需要显示的HTML标签,经过摸索实验,发现了一个非常好用的第三方组件-HTMLView。HTMLView是一个可以使用HTML内容并将其渲染为Native视图的第三方组件,它具有自定义样式和链接处理等特性。

    1. 安装

    使用npm包管理工具安装第三方组件库HTMLView。

    npm install react-native-htmlview --save
    

    2. 用法

    Props:

    HtmlView.propTypes = {
      addLineBreaks: PropTypes.bool,
      bullet: PropTypes.string,
      lineBreak: PropTypes.string,
      NodeComponent: PropTypes.func,
      nodeComponentProps: PropTypes.object,
      onError: PropTypes.func,
      onLinkPress: PropTypes.func,
      onLinkLongPress: PropTypes.func,
      paragraphBreak: PropTypes.string,
      renderNode: PropTypes.func,
      RootComponent: PropTypes.func,
      rootComponentProps: PropTypes.object,
      style: ViewPropTypes.style,
      stylesheet: PropTypes.object,
      TextComponent: PropTypes.func,
      textComponentProps: PropTypes.object,
      value: PropTypes.string,
    };
    
    HtmlView.defaultProps = {
      addLineBreaks: true,
      onLinkPress: url => Linking.openURL(url),
      onLinkLongPress: null,
      onError: console.error.bind(console),
      RootComponent: element => <View {...element} />, // eslint-disable-line react/display-name
    };
    

    上面这些就是HTMLView所具有的prop,常用如下:

    • value:要显示的HTML内容字符串
    • onLindPress:点按HTMLView的链接时会通过url调用这个函数,通过这个属性将会覆盖链接的处理方式(默认调用Linking.openURL(url))。
    • onLinkLongPress:长按HTMLView的链接时通过url调用这个函数。默认值为null。
    • stylesheet:一个由标签名称作为键值的样式表对象,它将覆盖应用于相应标签的样式。

    3. 例子

    import React,{Component} from 'react'
    import {StyleSheet} from 'react-native'
    import HTMLView from 'react-native-htmlview';
    
    class App extends React.Component {
      render() {
        var agreeContent = '<p>请查看<a href="https://www.baidu.com" target="_blank">隐私条款</a><br></p>';
        return (
          <HTMLView
            value={agreeContent}
            stylesheet={styles}
            onLinkPress={(url) => this._loadWebView(url)}
          />
        );
      }
      _loadWebView(url) {
        // 打开url
      }
    }
     
    const styles = StyleSheet.create({
      p:{
        fontSize:11,
        marginTop:2.5,
        marginLeft:5
      },
      a:{
        color:'#FF6700'
      }
    });
    

    注意:要修改HTMLView组件的内容样式,只能通过stylesheet这个prop。如样例所示通过标签名作为键值的样式表对象去改变THMLView组件的内容样式。

    参考

    react-native-htmlview

    相关文章

      网友评论

          本文标题:React Native HTMLView

          本文链接:https://www.haomeiwen.com/subject/wjxmektx.html