响应本机AlertIOS回调

时间:2016-09-19 12:28:27

标签: react-native alert

当我点击取消按钮时,它显示" 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}),
    },
    ]
  );
 }
}

2 个答案:

答案 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)