我想安装这个库:https://github.com/zo0r/react-native-push-notification。
它说要这样做:
var PushNotification = require('react-native-push-notification');
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function(token) {
console.log( 'TOKEN:', token );
},
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
},
// ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
senderID: "YOUR GCM SENDER ID",
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true,
});
我的问题是,我将把这个配置放在哪里?我真的不想通过将其放入componentWillMount
或componentDidMount
来污染我的组件。我还想从不同的组件发送推送通知,所以我想配置一次,然后全局使用它。
查看文档后,您似乎将该配置样板放在顶部范围(即根本不在组件中),然后调用 PushNotification 的成员函数来发送通知。 如果我正在组织一个项目,我可能会将其放在自己的 js 文件中并导出 PushNotification 对象,然后在需要发送推送通知的组件中导入或要求它。
假设你使用的是 ES6,你会做这样的事情:
推送通知.js
import PushNotification from 'react-native-push-notification';
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
},
});
export default PushNotification;
我的组件.js
import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';
import PushNotification from './PushNotification';
class MyComponent extends Component {
componentDidMount() {
PushNotification.localNotification({
message: 'MyComponent mounted!'
});
}
render() {
return (
<Text>Hello world!</Text>
);
}
}
AppRegistry.registerComponent('MyComponent', () => MyComponent);