我想在Web视图没有Internet时显示一条没有Internet的消息。我搜索有关它的东西,但没有找到它。有人能帮我吗 ?抱歉,我是react-native的新手。
编辑1 `
import React, { Component } from 'react'
import { StyleSheet, Text, View, NetInfo } from 'react-native';
import WebViewComp from './web_view_comp.js'
export default class App extends Component {
constructor(){
super();
this.state={
connection_Status : ""
}
}
componentDidMount() {
NetInfo.isConnected.addEventListener(
'connectionChange',
this._handleConnectivityChange
);
NetInfo.isConnected.fetch().done((isConnected) => {
if(isConnected == true){
this.setState({connection_Status : "Online"})
}
else{
this.setState({connection_Status : "Offline"})
}
});
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener(
'connectionChange',
this._handleConnectivityChange
);
}
_handleConnectivityChange = (isConnected) => {
if(isConnected == true){
this.setState({connection_Status : "Online"})
}
else{
this.setState({connection_Status : "Offline"})
}
};
render() {
if (this.state.connection_Status == "Online") {
return (
<WebViewComp/>
)
} else {
return (
<View style={styles.MainContainer}>
<Text style={{fontSize: 20, textAlign: 'center', marginBottom: 20}}> Você está { this.state.connection_Status }</Text>
</View>
)
}
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
padding: 20
},
TextStyle: {
fontSize:20,
textAlign: 'center',
}
});
`
我根据帮助编辑了代码,得到了这个结果,但是我相信,如果此人已连接了移动互联网并且没有移动数据,则会出现问题。
答案 0 :(得分:0)
react-native的WebView有一个道具调用onMessage
,您可以使用它来了解没有互联网时的URL响应。
onWebViewMessage(event: any) {
let msgData;
try {
// msgData will have the url from webview
// and event have another props
msgData = event.nativeEvent.data;
// check and do something
} catch (err) {
console.warn(err);
return;
}
...
}
<WebView
source={{ uri: "http://www.youtube.com/" }}
onMessage={this.onWebViewMessage}
...
/>
我希望能对您有所帮助,我不记得确切地如何使用它,但是我认为这是一个很好的开始方式
答案 1 :(得分:0)
您可以像这样使用onError
的{{1}}事件:
WebView
如果您想知道是否有互联网,请跟踪//declarations and imports
state={isError:false}
render(){
return(
<WebView onError={()=>alert("Something went wrong")} />
)}
的错误。
答案 2 :(得分:0)
您可以使用React Native NetInfo,这是来自文档的示例:
NetInfo.isConnected.fetch().then(isConnected => {
console.log('First, is ' + (isConnected ? 'online' : 'offline'));
});
function handleFirstConnectivityChange(isConnected) {
console.log('Then, is ' + (isConnected ? 'online' : 'offline'));
NetInfo.isConnected.removeEventListener(
'connectionChange',
handleFirstConnectivityChange
);
}
NetInfo.isConnected.addEventListener(
'connectionChange',
handleFirstConnectivityChange
);
如果您要检查特定的URL,可以发送请求并更新状态
let req =等待fetch('https://www.someurl.com'); let isConnected = req.status === 200;