iOS工程实践

react-native webView加载网页问题

2017-11-14  本文已影响1620人  sybil052

现在有这么一个需求,app的界面上需要加载一个二维码,但是后台不能返回图片地址,只能返回一个网页地址,怎么实现?
很多人会说当然是用webView加载网页啦,webView支持载入一段静态的html代码或是一个url。这时,问题来了,怎么让二维码居中显示在手机界面上呢?
我想到了以下几种方案:

下面我们来分析下三种方法~

方法一

先上代码:

...
let html = '<div style="height: 300px">'
            + '<iframe width="100%" height="100%" src="网页地址"></iframe>'
            + '</div>';
...
    <View style={styles.imageView}>
        <WebView
             style={{
                 height: 150,
                 width: 150,
                 alignItems: 'center',
             }}
             source={{html: html}}
             javaScriptEnabled={true}
             domStorageEnabled={true}
             scalesPageToFit={true}
         />
     </View>

运行后发现并不如意,在界面显示的二维码周围会有一个边框,很不美观,这个方法pass!

方法二
    <View style={styles.imageView}>
        <WebView
             style={{
                 height: 150,
                 width: 150,
                 alignItems: 'center',
             }}
             source={{url:网页中的图片地址}}
             javaScriptEnabled={true}
             domStorageEnabled={true}
             scalesPageToFit={true}
         />
     </View>

这个方法显示倒是可以,但网页地址是不断变化的,那图片的地址也在不断变化,可以预料到肯定有bug存在,这种方式貌似不太合适!

方法三
<View style={styles.imageView}>
        <WebView
             style={{
                 height: 150,
                 width: 150,
                 alignItems: 'center',
                 paddingRight:10
             }}
             source={{url: this.state.url}}
             javaScriptEnabled={true}
             domStorageEnabled={true}
             scalesPageToFit={false}
             injectedJavaScript="var img = document.getElementsByTagName('img')[0];
             img.style.cssText = 'width: 130px; height:130px;'"
         />
     </View>

这种方式完美显示,injectedJavaScript属性就是设置在网页加载之前注入的一段JS代码。我们可以通过injectedJavaScript,在网页加载之前改变网页的css样式,这样就完美解决网页显示大小不合适,不居中的问题了~
上张效果图:

sybil052-144201@2x.png
上一篇 下一篇

猜你喜欢

热点阅读