我正在寻找安装此库: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
来污染我的组件。我还想从不同的组件发送推送通知,所以我想配置一次,然后全局使用它。
答案 0 :(得分:1)
在查看文档之后,看起来您将该配置样板放在顶部范围内(即根本不在组件中),然后调用PushNotification的成员函数来发送通知。如果我正在组织一个项目,我可能会把它放在自己的js文件中并导出PushNotification对象,然后在需要发送推送通知的组件中导入或要求它。
假设您正在使用ES6,您可以这样做:
<强> PushNotification.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;
<强> MyComponent.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);