在用react native 做開發(fā)的時候杈抢,用到了Webview這個組件觉鼻,而WebView這個組件還是有不少坑的
坑點1: scalesPageToFit 這個適配屏幕的屬性
return ( <WebView
ref = 'awebView'
style={styles.webStyle}
source={{uri: this.state.url, method: 'POST',body : this.state.webViewBody}} // onLoadStart={this.loadStart()}
startInLoadingState={true}
onMessage={this._onMessage}
javaScriptEnabled={true}
/>)
代碼就在上面的侵俗;在iOS沒問題禀晓,網(wǎng)頁可以自適應(yīng)莉擒,但是在Android平臺上就出問題了棒动,屏幕無法適配,scalesPageToFit 這個屬性就是適配屏幕的叨叙,設(shè)置是否要把網(wǎng)頁縮放到適應(yīng)視圖的大小锭弊,以及是否允許用戶改變縮放比例。但是死活就是無法適配擂错;后面看了webView 的源碼 發(fā)現(xiàn)
@ReactProp(name = "scalesPageToFit")
public void setScalesPageToFit(WebView view, boolean enabled) {
view.getSettings().setUseWideViewPort(!enabled);
}
在Android 中是取反的味滞;
所以必須
scalesPageToFit={Platform.OS === 'ios'? true : false}
這樣就OK了
坑點2:地址有中文解析不了
<WebView source={{uri: "https://www.aaaa.com?userName=張三"}}
/>
如上面地址一樣,React Native webView顯示404 钮呀,這才發(fā)現(xiàn)webView 中有中文或者一些特殊的字符是解析不了 ??的剑鞍;得先編碼一下
let userName = encodeURIComponent(this.props.navigation.state.params.userName);
let url = "https://www.aaaa.com?" +'userName=' + userName;
<WebView source={{uri: url}}
/>
這樣就OK了
坑點3:ReactNative webview組件android不支持type="file" 打開相機和相冊
ReactNative WebView里面type="file"安卓版本無效,因為ReactNative的WebView組件里面使用的是原生組件爽醋,而安卓的webview原生組件默認(rèn)是不支持上傳和下載的蚁署,IOS是支持的,所以才會出現(xiàn)這種問題蚂四。
解決辦法:ReactNative里面的webview使用第三方組件:https://github.com/lucasferreira/react-native-webview-android