react native关于在ScrollView里使用WebView会有大片多余空白的问题

本人也是react native的菜鸟,下面只是说说解决方案,具体为什么可以实现目前还不懂。

我在项目里因为需求关系,在ScrollView里放置了WebView。

方法一:
一开始我按照网上的一些方法在js里的代码如下:

 1 <ScrollView>
 2   <WebView
 3     ref={'webview'}
 4     source={{ html: data.html }}
 5     style={{  height: this.state.WebViewHeight }}
 6     scrollEnabled = {false}
 7     onNavigationStateChange={(title)=>{
 8       this.setState({
 9         WebViewHeight: (parseInt(title.title))
10       })
11     }}
12     onMessage={(e) => {
13       this.handleMessage(e)
14     }}
15   />
16   ...
17 </ScrollView>

在data.html里的代码如下:

 1 <!DOCTYPE html> 
 2   <html lang="en">
 3   <head>
 4     <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
 5   </head>
 6   <body>
 7     ...
 8   </body>
 9   <script>
10     window.onload = function () {
11       window.location.hash = 1;
12       document.title = document.body.clientHeight;
13      } 
14   </script>
15   </body>
16   </html>

但是这种方法,在从别的页面第一次跳到webView所在的页面时,webView的高度是没问题的,但是第二次的高度就不对了。

方法二:

后来我就想了另外一种方法,在js里的代码如下:

 1 <ScrollView>
 2   <WebView
 3     ref={'webview'}
 4     source={{ html: data.html }}
 5     style={{  height: this.state.WebViewHeight }}
 6     scrollEnabled = {false}
 7     onMessage={(e) => {
 8       this.handleMessage(e)
 9     }}
10     onLoadEnd={this.webViewLoaded}
11     javaScriptEnabled={true}
12   />
13   ...
14 </ScrollView>

就是我不采用onNavigationStateChange,而是通过onLoadEnd来改变height的值,onLoadEnd里调用的webViewLoaded函数代码如下:

1 webViewLoaded = () => {
2     console.log('loaded ', this.refs.myWebView);
3     this.refs.webview.injectJavaScript(`
4       const height = document.body.clientHeight;
5       window.postMessage(JSON.stringify({height: height}));
6     `);
7   }

在onMessage里调用的handleMessage监听传过来的height值,如下:

1 handleMessage = (e) => {
2     const data = JSON.parse(e.nativeEvent.data);
3     if (data.height) {
4         this.setState({
5           WebViewHeight: data.height
6         });
7     }
8 }

这种方法在调试阶段的时候,是没问题了,没有出现大片空白,加载情况也正常,但是在打包成apk后,页面里WebView的加载出正确的高度的速度变得极度缓慢。
方案三:

最后我这边的解决方案就是综合方案1和方案2:
如下:

 1 <ScrollView>
 2    <WebView
 3     ref={'webview'}
 4      source={{ html: data.html }}
 5      style={{  height: this.state.WebViewHeight }}
 6      scrollEnabled = {false}
 7     onMessage={(e) => {
 8        this.handleMessage(e)
 9      }}
10      onNavigationStateChange={(title)=>{
11        this.setState({
12          WebViewHeight: parseInt(title.title)
13        })
14      }}
15      onLoadEnd={this.webViewLoaded}
16      javaScriptEnabled={true}
17    />
18    ...
19 </ScrollView>

这样在打包成apk后,WebView获取正确高度的时间就会短了,而且第二次进入也不会再出现多余空白的问题了。

猜你喜欢

转载自www.cnblogs.com/LXY02/p/9023476.html