反应本机 AlertIOS 回调

React native AlertIOS callback

当我点击取消按钮时,它显示 "undefined is not an object"。代码如下所示。

更新:

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}),
    },
    ]
  );
 }
}

您收到此错误是因为 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}),
  },
  ]
);
}

如果你愿意,你也可以简单地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 main函数让他们可以访问this,所以:

this._onRemoteNotification变成了this._onRemoteNotification.bind(this)