簡體   English   中英

在 React 上實現 react-notification-system

[英]Implementing react-notification-system on React

我正在嘗試實施 react-notification-system: https : //github.com/igorprado/react-notification-system,但無法使其正常工作。 我的代碼:

// on the view

constructor() {
    super();
    this.state = {};
    this.state._notificationSystem = null;
    this.state = getProfileState();
}

componentDidMount() {
    TimelineStore.addChangeListener(this._onChange.bind(this));
    this._notificationSystem = this.refs.notificationSystem;
}

render () {
    <NotificationSystem ref="notificationSystem" />
}

// on the actions

createEvent(e) {
    e.preventDefault();
    this.props._notificationSystem.addNotification({
      message: 'Notification message',
      level: 'success'
    });
    this.props.closeModal();
}

我收到錯誤:

Uncaught TypeError: Cannot read property 'addNotification' of undefined

我猜這是范圍的問題,但無法弄清楚如何解決它。

我無法理解你的例子。 提到的操作是在呈現 NotificationSystem 的同一組件中定義的? 或者您是否試圖通過道具將 NotificationSystem 的實例傳遞給另一個組件?

好吧,如果視圖和動作在同一個組件中,你需要像這樣調用你的動作:

this._notificationSystem.addNotification({
  message: 'Notification message',
  level: 'success'
});

現在,如果您嘗試通過 props 將其傳遞給另一個組件,則需要傳遞一個函數,如下所示:

// view

_notificationSystem = null

_getNotificationSystemInstance() {
  return this._notificationSystem
}

componentDidMount() {
  this._notificationSystem = this.refs.notificationSystem;
}

render() {
  return (
    <div>
      <EventComponent notification={ this._getNotificationSystemInstance } />
      <NotificationSystem ref="notificationSystem" />
    </div>
  );
}

// event component
createEvent(e) {
  e.preventDefault();
  this.props.notification().addNotification({
    message: 'Notification message',
    level: 'success'
  });
  this.props.closeModal();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM