当我点击取消按钮时,它显示" undefined不是对象"。代码如下所示。
更新
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 :(得分: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}),
},
]
);
}
答案 1 :(得分: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)