2016-02-25 74 views
1

我想回到以前的觀點在我使用此代碼返回鍵反應android原生

'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的特性 '道具' @ d:\陣營\高良\ node_modules \反應母語\庫\ JavaScriptAppEngine \初始化\ ExceptionsMana ...:61handleError @ d:\陣營\高良\ 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:\陣營\高良\ node_modules \反應母語\庫\公用\ MessageQueue.js:86onmessage @ debuggerWorker.js:39

enter image description here

我想這是this.props無法訪問但是我不知道如何克服這個問題。如果我把BackAndroid.addEventListener它給人的類中我錯誤

UnExpectedToken

回答

7

編輯:BackAndroid現在已經過時。您應該使用BackHandler來代替。

在你的活動中,this並不是指你認爲它指的是什麼。 在這種情況下,它指的是事件被調用的對象。

我在我的反應原生應用程序中做到這一點的方法是通過在我的主要組件(其中呈現Navigator的組件)的componentDidMount()函數中添加事件。

我添加它那裏(那種)以下方式:

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()。所以它在第一次渲染之後立即添加事件。它只會被解僱一次,所以沒有重疊的事件和類似的東西。

但是,我不會在場景中添加事件偵聽器。它帶來了可能增加事件兩次的風險。雖然我不確定是否兩次添加該事件實際上會改變任何內容。

+0

感謝您的回答。它的工作,但與'this.props.navigator.pop();'而不是'this.navigator.pop();'..編輯答案接受它 –

+0

哦,看看那一個。很高興它可以幫助,雖然 – stinodes

+0

@Sinitodes這不適用於我:/它給了我這個錯誤'未定義不是一個對象(評估'this.props.navigator.pop()')'。我有你在我的導航器組件中發佈的完全相同的代碼。 – corasan