我正在开发一个聊天应用程序,每次我发送一条消息时,我都需要滚动到底部才能看到新消息。因此,就像在常规聊天中一样,我需要提供这样的功能,即用户无需手动滚动到底部就可以看到最后一条消息。
我正在使用 React,有没有 css 方式?或者你能告诉我最好的方法吗?
让我给你看一些代码
这是主要的组成部分
render () {
let messages = this.props.chatMessages.map((message) => {
return <ChatItem info={message.info} me={message.me} player={message.player} message={message.message} />;
});
let chatForm;
if (this.props.mode === 'player') {
chatForm = <ChatForm onAddMessage={this.addMessage} />;
}
return <div className="Chat">
<ul className="Chat__messages">{messages}</ul>
<hr />
<div>{chatForm}</div>
</div>;
}
这里是 ChatItem
和 ChatForm
组件
render () {
let item;
const { message, player, me, info } = this.props;
if (info) {
item = <li><em>{message}</em></li>;
}
else if (me) {
item = <li><strong>Me: {message}</strong></li>;
}
else {
item = <li><strong>{player}:</strong> {message}</li>;
}
return item;
}
render () {
return <div className="ChatForm">
<input
className="ChatForm__input"
placeholder="Your message..."
ref="newMessage"
onKeyDown={this.onKeyDown}
autofocus="true" />
</div>;
}
添加信息
我需要这样的东西 http://codepen.io/TimPietrusky/pen/ylkFs
看这部分
// Scroll the latest line of output
output.scrollTop(
output[0].scrollHeight - output.height()
);
我应该如何使其适应我在 React 上的代码?
最佳答案
一种方法是比较生命周期事件中的当前和上一个/下一个 Prop ,例如 componentDidUpdate
并在添加新消息时滚动到底部。例如:
componentDidUpdate(prevProps) {
// Check if new message was added, for example:
if (this.props.messages.length === prevProps.messages.length + 1) {
// Scroll to bottom
}
}
关于javascript - 自动滚动到消息底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32060781/