2016-09-19 88 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