【发布时间】:2015-09-24 17:08:46
【问题描述】:
我正在使用 React,并且正在开发一个聊天应用程序。就像你现在一样,每次聊天屏幕中有新消息或任何事件时,最后一个事件/项目/消息都应该成为焦点,这样用户就不必向下滚动以在聊天中查找新事件。作为一个普通的聊天应用。
每个事件都附加到this.props.chatMessages。
我已经完成了此行为,但仅在用户添加新消息时完成。我需要这个功能来处理所有事情,有时聊天会说
新用户已添加到聊天中
或
用户 XXXXX 离开了聊天室
所以,这些是不同的事件,它们是信息性消息,而不是常规用户消息。
正如我之前提到的,每个新事件都附加到this.props.chatMessages
当用户自己发送消息时,我这样做是为了专注于最后一条消息
constructor (props) {
super(props);
this.addMessage = this.addMessage.bind(this);
this.focusOnLastMessage = this.focusOnLastMessage.bind(this);
ChatActions.connect({ socketUrl : this.props.socket, mode : this.props.mode, room : this.props.room, user : this.props.user });
}
addMessage (text) {
if (text.length) {
ChatActions.addMessage(text);
this.focusOnLastMessage();
}
}
focusOnLastMessage () {
console.log(this.props.chatMessages);
let lastMessage = React.findDOMNode(this.refs.messages);
lastMessage.scrollTop = lastMessage.scrollHeight;
}
在渲染方法中我有这样的东西
chatForm = <ChatForm onAddMessage={this.addMessage} />;
这里是完整的功能以防万一。您在哪里看到 <ChatItem .../> 是因为它是可视化聊天中发生的每个新事件的组件。
class ChatView extends React.Component {
static getStores () {
return [ ChatStore ];
}
static getPropsFromStores () {
return ChatStore.getState();
}
constructor (props) {
super(props);
this.addMessage = this.addMessage.bind(this);
this.focusOnLastMessage = this.focusOnLastMessage.bind(this);
ChatActions.connect({ socketUrl : this.props.socket, mode : this.props.mode, room : this.props.room, user : this.props.user });
}
addMessage (text) {
if (text.length) {
ChatActions.addMessage(text);
this.focusOnLastMessage();
}
}
focusOnLastMessage () {
console.log(this.props.chatMessages);
let lastMessage = React.findDOMNode(this.refs.messages);
lastMessage.scrollTop = lastMessage.scrollHeight;
}
render () {
let messages = this.props.chatMessages.map((message) => {
return <ChatItem info={message.info} me={message.me} player={message.player} message={message.message}
onNewEvent={this.focusOnLastMessage} />;
}), chatForm, hr, dealerPlayerMessages, dealerPlayerBox, minusPlusButtons;
if (this.props.mode === 'player') {
dealerPlayerMessages = <ul ref="messages">{messages}</ul>;
hr = <hr />;
chatForm = <ChatForm onAddMessage={this.addMessage} />;
dealerPlayerBox = <div>{dealerPlayerMessages}{hr}{chatForm}</div>
}
if (this.props.mode === 'dealer') {
minusPlusButtons = <MinusPlusButtons />
dealerPlayerMessages = <ul ref="messages">{messages}</ul>;
dealerPlayerBox = <div> {minusPlusButtons} {dealerPlayerMessages}</div>
}
return <div>
{dealerPlayerBox}
</div>;
}
}
那么,我应该怎么做才能倾听this.props.chatMessages 的每一个变化,以便专注于聊天中的每一个新项目?
【问题讨论】:
-
componentWillReceiveProps生命周期方法怎么样? -
@azium 我正在阅读,但不知道如何使其适应我的代码,您能帮帮我吗?请。
标签: javascript reactjs