gpt4 book ai didi

react-native - React Native WebView App 不会在按下后退按钮时退出

转载 作者:行者123 更新时间:2023-12-03 16:43:52 26 4
gpt4 key购买 nike

在按下后退按钮设置返回功能后,React Native WebView 应用程序不会在按下后退按钮时退出。我想在 webview 不在主页上时按下后退按钮返回功能,当 webview 在主页上时然后退出应用程序。

export default class WebView extends Component {

constructor (props) {
super(props);
this.WEBVIEW_REF = React.createRef();
}

componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}

componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}

handleBackButton = ()=>{
this.WEBVIEW_REF.current.goBack();
return true;
}

onNavigationStateChange(navState) {
this.setState({
canGoBack: navState.canGoBack
});
}


render(){
return (
<WebView
source={{ uri: 'https://stackoverflow.com' }}
ref={this.WEBVIEW_REF}
onNavigationStateChange={this.onNavigationStateChange.bind(this)}

/>
);
}
}

最佳答案

由于您正在管理 canGoBack 的状态内onNavigationStateChange功能,更改您的 handleBackButton功能如下,

handleBackButton = () => {
if (this.state.canGoBack) {
this.WEBVIEW_REF.current.goBack();
return true;
}
}

检查下面的完整示例
import React, { Component } from "react";
import { BackHandler } from "react-native";
import { WebView } from "react-native-webview";

export default class App extends Component {
WEBVIEW_REF = React.createRef();

state = {
canGoBack: false,
};

componentDidMount() {
BackHandler.addEventListener("hardwareBackPress", this.handleBackButton);
}

componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.handleBackButton);
}

handleBackButton = () => {
if (this.state.canGoBack) {
this.WEBVIEW_REF.current.goBack();
return true;
}
};

onNavigationStateChange = (navState) => {
this.setState({
canGoBack: navState.canGoBack,
});
};

render() {
return (
<WebView
source={{ uri: "https://stackoverflow.com" }}
ref={this.WEBVIEW_REF}
onNavigationStateChange={this.onNavigationStateChange}
/>
);
}
}

希望这对你有帮助。如有疑问,请放心。

关于react-native - React Native WebView App 不会在按下后退按钮时退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61102977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com