在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
web