我想建立一个聊天系统,当进入窗口和有新消息进来时自动滚动到底部。React中如何自动滚动到容器的底部?
请您参考如下方法:
正如 Tushar 提到的,您可以在聊天底部保留一个虚拟 div:
render () {
return (
<div>
<div className="MessageContainer" >
<div className="MessagesList">
{this.renderMessages()}
</div>
<div style={{ float:"left", clear: "both" }}
ref={(el) => { this.messagesEnd = el; }}>
</div>
</div>
</div>
);
}
然后每当您的组件更新时滚动到它(即添加新消息时更新状态):
scrollToBottom = () => {
this.messagesEnd.scrollIntoView({ behavior: "smooth" });
}
componentDidMount() {
this.scrollToBottom();
}
componentDidUpdate() {
this.scrollToBottom();
}
我正在使用标准Element.scrollIntoView方法在这里。