在用react native 做开发的时候,用到了Webview这个组件,基本用法可以参考:
https://reactnative.cn/docs/0.51/webview.html#content
我的代码大概:
render() {
console.log("99999" + this.state.loaderr)
if (!this.state.loaderr) {
return (
<View
style={{
width: width,
height: height,
// paddingBottom: 85,
backgroundColor: 'white'
}}
>
<Header navigation={this.props.navigation} name={'技能'}/>
<WebView
refs="webview"
style={{
// flex: 1,
// backgroundColor: 'white',
width: width,
// marginBottom: 85,
}
}
automaticallyAdjustContentInsets={true}
javaScriptEnabled={true}
saveFormDataDisabled={true}
scalesPageToFit={true}
contentInset={{top:0,left:0,right:0,bottom:0}}
// domStorageEnabled={true}
// startInLoadingState={true}
onError={this.onError.bind(this)}
onMessage={this.onMessage.bind(this)}
source={{ uri: global.mantic_skill_url + 'apps/aiskill.html', method: 'GET' }}
/>
</View>
);
} else {
return (
<View>
<Header navigation={this.props.navigation} />
<TouchableOpacity style={styles.container} onPress={this.testForceFun.bind(this)}>
<View style={styles.loading}>
<Image source={require('./../../img/net_failed.png')} style={styles.searchEmpty}></Image>
<Text style={{ color: 'gray', fontSize: 16 }}>网络连接失败,点击重试</Text>
</View>
</TouchableOpacity>
</View>
)
}
但是 在ios 手机上是OK的,h5网页可以自适应,但是在Android平台上就出问题了,屏幕无法适配,scalesPageToFit 这个属性就是适配屏幕的,设置是否要把网页缩放到适应视图的大小,以及是否允许用户改变缩放比例。但是死活就是无法适配,
然后网上各种资料查找,比较少,于是查看Webview源码:
路径:
./node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/views/webview
在ReactWebViewManager.java 里 我看到了这段代码:
@ReactProp(name = "scalesPageToFit")
public void setScalesPageToFit(WebView view, boolean enabled) {
view.getSettings().setUseWideViewPort(!enabled);
}
卧槽。。。。竟然取反了,,。。
于是我把scalesPageToFit={true} ,试了一把果然 OK啦。。。
应该算是一个React native的一个bug了吧,
最终这样写适配双平台:
scalesPageToFit={Platform.OS === 'ios'? true : false}