2016-09-19 90 views
0

當我點擊取消按鈕,它顯示「未定義不是一個對象」。代碼如下所示。反應本地AlertIOS回調

更新:

componentWillMount() { 
    PushNotificationIOS.addEventListener('notification', this._onRemoteNotification); 
} 

_onRemoteNotification(notification) { 
    AlertIOS.alert(
    'Push Notification Received', 
    'Alert message: ' + notification.getMessage(), 
    [{ 
     text: 'OK', 
     onPress: null, 
    }, 
    { 
     text: 'Cancel', 
     onPress:()=>this.setState({key: value}), 
    }, 
    ] 
); 
} 
} 
+0

你能告訴你如何調用這個警報在您的組件? – rclai

+0

已更新。請檢查 – bns

回答

0

如果你願意,你也可以簡單地bind的功能和它外化這樣的:

onAlertCancel() { 
    this.setState({key: value}); 
} 

AlertIOS.alert(
    'Push Notification Received', 
    'Alert message: ' + notification.getMessage(), 
    [{ 
    text: 'OK', 
    onPress: null, 
    }, 
    { 
    text: 'Cancel', 
    onPress: this.onAlertCancel.bind(this), 
    }, 
    ] 
); 
} 

而且不要忘了bind主要功能,讓他們訪問到this,所以:

this._onRemoteNotification成爲this._onRemoteNotification.bind(this)

+0

感謝您的回覆。我嘗試過,但它顯示undefined不是一個對象(評估'this.onAlertCancel') – bns

+0

好吧我知道爲什麼,在這一行中'PushNotificationIOS.addEventListener('notification',this._onRemoteNotification);'只是綁定功能:' this._onRemoteNotification.bind(this)',它將函數綁定到類,所以在此之後,這將不再是未定義的! –

+0

固定。非常感謝你。有沒有使用綁定的任何解釋?我應該何時使用以及什麼時候不需要? – bns

0

因爲this沒有內部AlertIOS.alert定義您收到此錯誤。函數調用之前,您必須引用您的組件。您的代碼看起來就像這樣:

var self = this; 

AlertIOS.alert(
    'Push Notification Received', 
    'Alert message: ' + notification.getMessage(), 
    [{ 
    text: 'OK', 
    onPress: null, 
    }, 
    { 
    text: 'Cancel', 
    onPress:()=>self.setState({key: value}), 
    }, 
    ] 
); 
} 
+0

感謝您的回覆。我試過,但它顯示undefined不是一個對象(評估'self.setState') – bns