0
陣營組件當我聽到一個'new-message'
事件我想打電話給我Dashboard
組件的createMessage
功能:訪問從插座IO聽衆
var socket = io.connect()
socket.on('new-message', (data) => {
console.log("ALL CLIENTS SHOULD GET THIS MESSAGE")
Dashboard.createMessage(data.id, data.body, data.context, data.urgent, data.customContext)
})
const Dashboard = React.createClass({
createMessage: function(id, body, context, urgent, customContext) {
this.setState({
messages: [
...this.state.messages,
{id: id, user_id: this.state.currentUser, body: body, context: context, urgent: urgent, customContext: customContext}
]
})
}
})
但是,我得到一個錯誤:Uncaught TypeError: Dashboard.createMessage is not a function
是否有從組件外部訪問Dashboard
createMessage
方法的方法?
或者是有辦法有Dashboard
component
總是監聽事件,我可以做這樣的事情:
var socket = io.connect()
const Dashboard = React.createClass({
alwaysListenForEvent: function() {
socket.on('new-message', (data) => {
console.log("ALL CLIENTS SHOULD GET THIS MESSAGE")
this.createMessage(data.id, data.body, data.context, data.urgent, data.customContext)
})
}
createMessage: function(id, body, context, urgent, customContext) {
this.setState({
messages: [
...this.state.messages,
{id: id, user_id: this.state.currentUser, body: body, context: context, urgent: urgent, customContext: customContext}
]
})
}
})