ReactNative WebView高度自适应

在ReactNative项目中可能会遇到展现HTML代码的状况,一般咱们会采用WebView来展现html代码,但ReactNative中的WebView须要设定高度才能展现出来,所以须要用js来计算文档高度作到高度自适应
具体代码实现以下:html

//这里我在初始化阶段定义初使高度
  constructor(props) {
    super(props);
    this.state={
      height:500,
    }
  }

//下面是WebView的代码。`${}`这个ES6中新加入的特性,容许经过反引号 ` 来建立字符串
//获取高度原理是当文档加载完后js获取文档高度而后添加到title标签中。这时经过监听导航状态变化的函数 `onNavigationStateChange` 来将title的值读取出来赋值给this.state.height从而使webview的高度作到自适应。
<View style={{height:this.state.height}}>
    <WebView
        source={{html: `<!DOCTYPE html><html><body>${htmlContent}<script>window.onload=function(){window.location.hash = 1;document.title = document.body.clientHeight;}</script></body></html>`}}
        style={{flex:1}}
        bounces={false}
        scrollEnabled={false}
        automaticallyAdjustContentInsets={true}
        contentInset={{top:0,left:0}}
        onNavigationStateChange={(title)=>{
          if(title.title != undefined) {
            this.setState({
              height:(parseInt(title.title)+20)
            })
          }
        }}
        >
    </WebView>
</View>

S61116-171231.jpg
clipboard.pngweb

相关文章
相关标签/搜索