首页 文章

返回键反应原生android

提问于
浏览
1

我正在尝试使用此代码返回到我的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;

在调试时,我看到后面的事件被成功检测到,但它在此行崩溃 this.props.navigator.pop() 给了我这个错误 .

无法读取undefinedhandleException的属性'props'@ D:\ React \ Kora \ node_modules \ react-native \ Libraries \ JavaScriptAppEngine \ Initialization \ ExceptionsMana ...:61handleError @ D:\ React \ Kora \ node_modules \ react-native \ Libraries \ JavaScriptAppEngine \ Initialization \ InitializeJava ...:80ErrorUtils.reportFatalError @ D:\ React \ Kora \ node_modules \ react-native \ packager \ react-packager \ src \ Resolver \ polyfills \ error-guard ....:28guard @ 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

enter image description here

我的猜测 this.props 不能在课堂支持旁边访问,但我不知道如何克服这个问题 . 如果我把 BackAndroid.addEventListener 放在课堂里它会给我错误

UnExpectedToken

1 回答

  • 7

    edit: BackAndroid is now deprecated. You should probably be using BackHandler instead.

    在您的活动中, this 没有提到您认为它所指的内容 . 在这种情况下,它指的是调用事件的对象 .

    我在react-native应用程序中执行此操作的方法是在主要组件的 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));
        }
    
        ...
    }
    

    It should work like this in your project.

    在初始渲染之后立即触发 componentDidMount() . 你也许可以使用 componentWillMount() . 因此它在第一次渲染之后立即添加事件 . 它只会被触发一次,因此没有重叠的事件和类似的东西 .

    但是,我不会在场景中添加事件监听器 . 它带来了两次可能添加事件的风险 . 虽然我不确定是否两次添加该事件实际上会改变任何事情 .

相关问题