我在Android反应原生应用程序中有一个Navigator。 我正在使用navigator.push()导航到另一个页面。看起来很自然,后退按钮会弹出导航器并返回一页,但这不是正在发生的事情。经过大量搜索,我得到了同样问题的功能,但我认为我放错了方式请看看这帮助了我。
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
} = React;
var SCREEN_WIDTH = require('Dimensions').get('window').width;
var BaseConfig = Navigator.SceneConfigs.FloatFromRight;
componentWillMount = () => {
BackAndroid.addEventListener('hardwareBackPress', () => Actions.pop());
};
var PageOne = React.createClass({
_handlePress() {
this.props.navigator.push({id: 2,});
},
render() {
return (
<View style={[styles.container, {backgroundColor: 'green'}]}>
<Text style={styles.welcome}>Greetings!</Text>
<TouchableOpacity onPress={this._handlePress}>
<View style={{paddingVertical: 10, paddingHorizontal: 20, backgroundColor: 'black'}}>
<Text style={styles.welcome}>Go to page two</Text>
</View>
</TouchableOpacity>
</View>
)
},
});
var PageTwo = React.createClass({
_handlePress() {
this.props.navigator.pop();
},
render() {
return (
<View style={[styles.container, {backgroundColor: 'purple'}]}>
<Text style={styles.welcome}>This is page two!</Text>
<TouchableOpacity onPress={this._handlePress}>
<View style={{paddingVertical: 10, paddingHorizontal: 20, backgroundColor: 'black'}}>
<Text style={styles.welcome}>Go back</Text>
</View>
</TouchableOpacity>
</View>
)
},
});
var SampleApp = React.createClass({
_renderScene(route, navigator) {
if (route.id === 1) {
return <PageOne navigator={navigator} />
} else if (route.id === 2) {
return <PageTwo navigator={navigator} />
}
},
_configureScene(route) {
return CustomSceneConfig;
},
render() {
return (
<Navigator
initialRoute={{id: 1, }}
renderScene={this._renderScene}
configureScene={this._configureScene} />
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: 'white',
},
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
module.exports = SampleApp;
答案 0 :(得分:1)
BackAndroid 应该返回 true 或 false 才能正常工作。
试试这个:
componentWillMount = () => {
BackAndroid.addEventListener('hardwareBackPress', () =>
const lengthOfNavigator = this.props.navigator.getCurrentRoutes();
if (lengthOfNavigator.length !== 1) {
this.props.navigator.pop();
return true;
} else {
return false;
}
);
};
getCurrentRoutes 用于获取导航器堆栈中推送的所有组件。