我正在 react-native 中创建一个 Webview,但是当我导航到任何页面并尝试导航回来时,应用程序会关闭。
我已经阅读了一些关于 STACK-OVERFLOW 的答案,并尝试了一些代码来处理 android 的后退按钮,但它没有帮助。
这是尝试过的代码:
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
BackHandler,
} from 'react-native';
import WebView from 'react-native-webview';
const App: () => React$Node = () => {
const [canBack, setCanBack] = useState(false);
useEffect(() => {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
console.log('mounted')
return () => {
this.backHandler.remove()
console.log('unmounted')
}
}, [canBack]);
handleBackPress = () => {
console.log('back btn pressed')
console.log('canBack is '+canBack)
if(canBack) {
this.refs[myWebView].goBack();
return true;
}
}
onNavigationChange = (navState) => {
console.log(navState);
// console.log(navState.canGoBack)
setCanBack(currentCanBack => navState.canGoBack);
console.log(canBack);
};
return (
<SafeAreaView style={{ flex: 1,}}>
<StatusBar barStyle="dark-content" />
<WebView
ref={(c) => {this.myWebView = c} }
source={{ uri: 'https://infinite.red' }}
domStorageEnabled={true}
onNavigationStateChange={(navState) => this.onNavigationChange(navState)}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
scrollView: {
flex: 1,
backgroundColor: 'lightgrey',
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
在这当我按下后退按钮时它给我错误“无法读取未定义反应本机的属性'#'”