我是新的反应本地人.我的应用程序中有两个页面.当我按下后退按钮时,我想打开上一页但是当我按下后退按钮时,应用程序会关闭.可以做些什么来解决这个问题?
我的代码是:
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TextInput,
TouchableHighlight
} from 'react-native';
import ToolbarAndroid from 'ToolbarAndroid';
import ActionButton from 'react-native-action-button';
import backAndroid from 'react-native-back-android';
import {hardwareBackPress} from 'react-native-back-android';
class AwesomeProject extends Component {
renderScene(route, navigator) {
if(route.name == 'HomePage') {
return <HomePage navigator={navigator} {...route.passProps} />
}
if(route.name == 'FormBuilderPage') {
return <FormBuilderPage navigator={navigator} {...route.passProps} />
}
}
render() {
return (
<Navigator
style={{ flex:1 }}
initialRoute={{ name: 'HomePage' }}
renderScene={ this.renderScene } />
)
}
}
class BackButtonEvent extends React.Component{
handleHardwareBackPress(){
if(this.sate.isOpen()){
this.handleClose();
return true;
}
}
}
var HomePage = React.createClass({
_navigate(name) {
this.props.navigator.push({
name: 'FormBuilderPage',
passProps: {
name: name
}
})
},
render() {
return (
<View style={styles.container}>
<ToolbarAndroid style = {styles.toolbar}>
<Text style = {styles.titleText}> Data Collector </Text>
</ToolbarAndroid>
<ActionButton
source = {require('./icon_container/ic_plus_circle_add_new_form.png')}
onPress = {this._navigate}
>
</ActionButton>
</View>
)
}
})
var FormBuilderPage = React.createClass({
render() {
return (
<View style={styles.container}>
<ToolbarAndroid style = {styles.toolbar}>
<TextInput placeholder = "Text here"/>
</ToolbarAndroid>
</View>
)
}
})
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
toolbar: {
height: 56,
backgroundColor: '#3F51B5'
},
titleText: {
color: '#fff',
}
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
最佳答案 您需要使用React Native的BackAndroid API.这是我的示例项目的片段.
BackAndroid.addEventListener('hardwareBackPress', () => {
var flag = false;
if(_route.name==="newbooking"){
Alert.alert(
"Confirmation",
"Are you sure you want to cancel?",
[
{text: 'No', onPress: () => console.log('OK Pressed!')},
{text: 'Yes', onPress: () => {_navigator.pop();}}
]
);
return true;
}
else{
flag = true;
}
if (_navigator.getCurrentRoutes().length === 1 ) {
return false;
}
if(flag){
_navigator.pop();
return true;
}
});
你可以看到我是如何实现here的!