Как отобразить всплывающее окно react-native-push-notification при нажатии кнопки?

#react-native

#react-native

Вопрос:

Я новичок в react native и изучаю react-native-notification-popup. Мне нужна небольшая помощь. В моем приложении componentDidMountFunction отображает уведомление при открытии экрана. Я хочу создать кнопку, и при нажатии на кнопку должно отображаться уведомление. Вот код:

 const renderCustomPopup = ({ appIconSource, appTitle, timeText, title, body }) => (
  <View>
    <Text>{title}</Text>
    <Text>{body}</Text>
    <Button title='My button' onPress={() => console.log('Popup button onPress!')} />
  </View>
);
export default class MyApp extends Component {
  componentDidMount() {
    this.popup.show({
      onPress: function() {console.log('Pressed')},
      appIconSource: require('./assets/icon.png'),
      appTitle: 'Some App',
      timeText: 'Now',
      title: 'Hello World',
      body: 'This is a sample message.nTesting emoji 😀',
      slideOutTime: 5000
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <NotificationPopup
          ref={ref => this.popup = ref}
          renderPopupContent={renderCustomPopup}
          shouldChildHandleResponderStart={true}
          shouldChildHandleResponderMove={true} />
      </View>
    );
  }
}
  

Чего я хочу, так это:

 export default class AddProfile extends Component {
    //...
    render() {    
    return (
      <View style={styles.container}>
        <TouchableOpacity 
          style={styles.btn}
          onPress={() => 
            //how to show same notification on onPress
            }
          >
          <Text style={styles.loginText}>Show Notification</Text>
        </TouchableOpacity>
      </View>

    );
  }
}
  

Ответ №1:

Просто переименуйте свою функцию componentDidMount и вызовите ее onPress. Нравится

 showPopUp= () => {
    this.popup.show({
      onPress: function() {console.log('Pressed')},
      appIconSource: require('./assets/icon.png'),
      appTitle: 'Some App',
      timeText: 'Now',
      title: 'Hello World',
      body: 'This is a sample message.nTesting emoji 😀',
      slideOutTime: 5000
    });
  }
  

И вызовите его таким образом:
onPress={() => this .showPopup()}
Измените свой класс как

 export default class AddProfile extends Component {
    //...
    render() {    
    return (
      <View style={styles.container}>
    <NotificationPopup
          ref={ref => this.popup = ref}
          renderPopupContent={renderCustomPopup}
          shouldChildHandleResponderStart={true}
          shouldChildHandleResponderMove={true} />
        <TouchableOpacity 
          style={styles.btn}
          onPress={() => this.showPopUp()
            }
          >
          <Text style={styles.loginText}>Show Notification</Text>
        </TouchableOpacity>
      </View>

    );
  }
}