2015-10-04 93 views
2

我正在尝试实现反应通知系统:https://github.com/igorprado/react-notification-system但无法使其工作。我的代码:在React上实现反应通知系统

// 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 

我猜测它是范围问题,但无法弄清楚如何解决它。

+0

我看到完全相同的问题!作为一个方面说明,你的构造函数内的逻辑是不正确的。它应该是'this._notificationSystem = null;'然后你将它设置在'componentDidMount'回调方法中。我也怀疑你必须使用'ReactDOM.findDOMNode(this.refs.notificationSystem)'来获取'NotificationSystem'的实例。尽管如此,它仍然不适用于我。 –

回答

1

我无法理解你的例子。所提及的操作是在您正在渲染NotificationSystem的相同组件中定义的?或者你是否试图通过道具将NotificationSystem的实例传递给另一个组件?

好吧,如果认为和行动是在同一组件,在你的行动,你需要这样的呼吁:

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

现在,如果你想通过道具将它传递给另一个组件,你需要通过如下功能:

// 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(); 
}