当webview加载无效的url时,我应该设置哪个属性来显示错误视图?我尝试了renderError,它触发了控制台消息但没有显示视图。
这是代码:
<View style={styles.webview_body}>
<WebView
source={{uri:this.props.url}}
onNavigationStateChange={this.onNavigationStateChange.bind(this)}
renderError={this.loadError.bind(this)}
/>
</View>
//the fucntion which display the error message
loadError(){
console.log('loaded');
return (
<View>
<Text>
something goes wrong.
</Text>
</View>
)
}
这是截图
[更新] 当我重新加载以清除错误时,会出现一个显示错误视图的临时状态。
答案 0 :(得分:4)
您可以使用onError
道具如下所示在出错后呈现视图,并尝试处理不同的WebView错误。 renderError
可用于呈现在解析WebView错误时显示的视图
onError={ (e) => {
let uri = new URI(this.props.url);
let host = uri.host();
let insecureHosts = [-1004, -6, -1202];//all error codes as displayed on your console
if(e){
//Handles NSURLErrorDomain in iOS and net:ERR_CONNECTION_REFUSED in Android
if(insecureHosts.indexOf(e.nativeEvent.code) !== -1){
this.setState({url: `http://${host}`});
}
//Handles Name resolution errors by redirecting to Google
else if(e.nativeEvent.code === -1003 || e.nativeEvent.code === -2){
this.setState({url: `https://www.google.com/#q=${host}`});
}
} else {
//loads the error view only after the resolving of the above errors has failed
return(
<View>
Error occurred while loading the page.
</View>
);
}}}
renderError={(e) => {
//Renders this view while resolving the error
return(
<View>
<ActivityIndicator
animating={ true }
color='#84888d'
size='large'
hidesWhenStopped={true}
style={{alignItems:'center', justifyContent:'center', padding:30, flex: 1}}/>
</View>
);
}}
请务必安装urijs并导入,以便使用URI
。