好吧,我有一个带有多个屏幕的react-native
应用程序,每个屏幕都有一个顶部栏,其中有一个后退按钮,它的主要行为是当按下此按钮时应用程序返回到主屏幕。我想要做的是将此行为复制到硬件后退按钮(现在通过按下应用程序关闭的硬件后退按钮),我该怎么做?
更新
我正在使用react-navigation
和redux
答案 0 :(得分:1)
因此,如果您使用react-navigation
和redux
,则可以查看docs - Handling the Hardware Back Button in Android
<强> YourComponent.js:强>
import React from "react";
import { BackHandler } from "react-native";
import { NavigationActions } from "react-navigation";
/* your other setup code here! this is not a runnable snippet */
class ReduxNavigation extends React.Component {
componentDidMount() {
BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
}
onBackPress = () => {
const { dispatch, nav } = this.props;
if (nav.index === 0) {
return false;
}
dispatch(NavigationActions.back());
return true;
};
render() {
/* more setup code here! this is not a runnable snippet */
return <AppNavigator navigation={navigation} />;
}
}
答案 1 :(得分:1)
你可以:
handleBackButton(){
this.props.navigation.popToTop();
return true;
}
popToTop返回堆栈中的第一个屏幕。
如果您正在使用Redux的react-navigation,则应将popToTop实现为要发送的操作。
答案 2 :(得分:0)
导入此包
this.exitApp = this.exitApp.bind(this);
在构造函数中绑定函数
<Button transparent onPress={this.exitApp}>
<Icon name="arrow-back" />
</Button>
你的后退按钮
exitApp() {
BackHandler.exitApp()
}
// Add the listener when the page is ready
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.exitApp);
}
// Remove the listener before removing
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.exitApp);
}
处理后退并关闭应用程序
ngIf..else
显示按钮的方式可能不同但这可行!如果有任何问题写在评论中。
答案 3 :(得分:0)
您可以通过以下示例
来完成import { BackHandler } from 'react-native';
class App extends Component {
constructor(props){
super(props);
this.backButtonClick = this.backButtonClick.bind(this);
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.backButtonClick);
}
componentWillUnmount(){
BackHandler.removeEventListener('hardwareBackPress', this.backButtonClick);
}
backButtonClick(){
if(this.props.navigation && this.props.navigation.goBack){
this.props.navigation.goBack(null);
return true;
}
return false;
}
}
答案 4 :(得分:0)
在功能组件中带有react Hooks 的实现
useEffect(() => {
function handleBackButton() {
navigation.navigate('register-phone');
return true;
}
const backHandler = BackHandler.addEventListener('hardwareBackPress', handleBackButton);
return () => backHandler.remove();
}, [navigation]);
不要忘记删除Unmount上的侦听器。