我按照以下代码重新创建了抽屉导航:https://github.com/mariodev12/react-native-menu-drawer-navigator
一切正常,但现在我不知道如何处理 native 按钮返回..我想总是返回到上一页,但如果你在主页中按两次退出应用程序。
这是我的代码:
App.js
import React from 'react';
import {StackNavigator} from 'react-navigation';
import DrawerStack from './src/stacks/drawerStack';
const Navigator = StackNavigator({
drawerStack: {screen: DrawerStack}
}, {
headerMode: 'none',
initialRouteName: 'drawerStack'
})
export default Navigator
drawerStack.js
import React from 'react'
import {StackNavigator, DrawerActions} from "react-navigation";
import {Text, View, TouchableOpacity} from 'react-native';
import Home from "../components/home";
import DrawerScreen from "./drawerScreen";
const DrawerNavigation = StackNavigator({
DrawerStack: {screen: DrawerScreen}
}, {
headerMode: 'float',
navigationOptions: ({navigation}) => ({
headerStyle: {
backgroundColor: 'rgb(255,45,85)',
paddingLeft: 10,
paddingRight: 10
},
title: 'Home',
headerTintColor: 'white',
headerLeft: <View>
<TouchableOpacity
onPress={() => {
if (navigation.state.isDrawerOpen === false) {
navigation.dispatch(DrawerActions.openDrawer());
} else {
navigation.dispatch(DrawerActions.closeDrawer());
}
}}>
<Text>Menu</Text>
</TouchableOpacity>
</View>
})
})
export default DrawerNavigation;
drawerScreen.js
import {DrawerNavigator} from 'react-navigation'
import Home from '../components/home';
import Login from '../components/login';
import Contacts from '../components/contacts';
import News from '../components/news';
const DrawerScreen = DrawerNavigator({
Home: {screen: Home},
Login: {screen: Login},
Contacts: {screen: Contacts},
News: {screen: News}
}, {
headerMode: 'none',
initialRouteName: 'Home'
})
export default DrawerScreen;
news.js "Example of one page"
import React from "react";
import {Text, View} from 'react-native';
export default class News extends React.Component {
render() {
return (
<View>
<Text> Here Leave the News!! </Text>
</View>
);
}
}
现在,我如何在标题中插入后退按钮而不是仅为“News.js”页面的经典菜单 (DrawerStack)?
最佳答案
在 Android 中,您必须使用 react-native 中的 BackHandler 自行处理后退按钮操作。
首先
import { BackHandler } from 'react-native';
在 ComponentDidMount 中添加一个事件监听器来监听 backpress:
componentDidMount() {
BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
}
在 ComponentwillUnmount 中确保移除监听器:
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
}
然后
onBackPress = () => {
//inside here do what you want with single back button
}
也请查看此链接: https://reactnavigation.org/docs/en/drawer-based-navigation.html
如果您想使用后退按钮返回上一个屏幕,抽屉式导航不适合您,您应该尝试使用 Stack Navigator。
关于android - React Native - 如何使用抽屉导航管理 native 后退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50737081/