我正在尝试使用以下代码返回我的react本机应用程序中的以前的视图。
'use strict';
var React = require('react-native');
var {
AppRegistry,
Component,
StyleSheet,
Text,
View,
BackAndroid,
Navigator
} = React;
var HomePage = require('./HomePage');
class DetailsPage extends Component{
constructor(props){
super(props);
}
render(){
return(
<View style={styles.container}>
<Text style={styles.text}>
{this.props.description}
</Text>
</View>
)
}
}
BackAndroid.addEventListener('hardwareBackPress', function() {
this.props.navigator.pop(); // line 32
return true;
});
var styles = StyleSheet.create({
container: {
flex: 1
},
text:{
color:'#000',
textAlign:'center',
fontWeight:'bold',
flex:1,
fontSize:20
},
});
module.exports = DetailsPage;在调试过程中,我看到back事件被成功检测到,但是它在这一行崩溃,this.props.navigator.pop()给了我这个错误。
无法读取D:\React\Kora\node_modules\react-native\Libraries\JavaScriptAppEngine\Initialization\ExceptionsMana…@ undefinedhandleException的属性“道具”@ D:\React\Kora\node_modules\react-native\Libraries\JavaScriptAppEngine\Initialization\InitializeJava…@61handleErrorD:\React\Kora\node_modules\react-native\packager\react-packager\src\Resolver\polyfills\error-guard.…@ :80ErrorUtils.reportFatalError:28卫士D:\React\Kora\node_modules\react-native\Libraries\Utilities\MessageQueue.js:43callFunctionReturnFlushedQueue D:\React\Kora\node_modules\react-native\Libraries\Utilities\MessageQueue.js:86onmessage @ debuggerWorker.js:39

我猜想this.props不能在类大括号的外面被访问,但是我不知道如何克服这个问题。如果我将BackAndroid.addEventListener放入类中,则会出现错误。
UnExpectedToken
发布于 2016-02-25 13:08:35
编辑:现在不推荐BackAndroid了。您可能应该使用 BackHandler 代替.。
在您的事件中,this没有提到您认为它所指的内容。在这种情况下,它引用调用事件的对象。
我在我的react本地应用程序中这样做的方法是在主组件的componentDidMount()-function中添加事件( Navigator是在其中呈现的组件)。
我以(某种程度上)如下方式添加了它:
class ViewComponent extends Component {
...
componentDidMount() {
//the '.bind(this)' makes sure 'this' refers to 'ViewComponent'
BackAndroid.addEventListener('hardwareBackPress', function() {
this.props.navigator.pop();
return true;
}.bind(this));
}
...
}它应该在您的项目中像这样工作.
componentDidMount()是在初始呈现之后立即触发的。您可能还可以使用componentWillMount()。因此,它在第一次呈现后立即添加事件。它只会被触发一次,所以没有重叠的事件和类似的事情。
但是,我不会在场景中添加事件侦听器。它带来了可能两次增加事件的风险。虽然我不确定添加两次这个事件是否真的会改变任何事情。
https://stackoverflow.com/questions/35627493
复制相似问题