目前我正在嘗試使用React和SockJS編寫簡單的聊天應用程序。我遇到的問題是當觸發socket.onmessage
時,我無法找到用於改變React類狀態的方法。這是我迄今寫的:如何顯示React類的狀態或任何方法?
/** @jsx React.DOM */
class Chatbox extends React.Component {
constructor() {
this.state = { messages: [] };
}
addMessage(message) {
let messages = this.state.messages;
message = "<span className=\"chat-message\">" + message + "</span>";
messages.push(message);
this.setState({ messages: messages });
}
clearChatbox() {
this.setState({ messages: [] });
}
render() {
return (
<div class="chatbox">
{this.state.messages.join("<br />")}
</div>
);
}
}
如果我錯過了其他任何錯誤,我會很感激,如果你能讓我知道。
編輯:這裏的主要問題不是我錯過的綁定(我只是一個愚蠢的錯誤),而是讓組件本身可以使用SockJS接收的消息。
更新:替補解決了我的情況很好的問題。當套接字連接接收其中添加的消息是由ChatboxActions處理的消息:
import React from 'react';
import ChatboxActions from '../actions/ChatboxActions';
import ChatboxStore from '../stores/ChatboxStore';
import connectToStores from 'alt/utils/connectToStores';
@connectToStores
class ChatBox extends React.Component {
constructor() {
super();
}
static getStores() {
return [ChatboxStore];
}
static getPropsFromStores(props) {
return ChatboxStore.getState();
}
static clearChatbox() {
alt.recycle(ChatboxStore);
}
render() {
<div className="chatbox">
{this.props.messages}
</div>
}
}
你缺少約束力。將'this.addMessage = this.addMessage.bind(this);'添加到您的構造函數中。相同 – knowbody
可能的重複http://stackoverflow.com/questions/31141444/reactjs-with-es6-this-props-is-not-a-function-when-i-communicate-two-components – knowbody