如何在react中滚动到底部?

我想建立一个聊天系统,并在进入窗口和收到新消息时自动滚动到底部。如何在React中自动滚动到容器底部

正如Tushar提到的,您可以在聊天的底部保留一个虚拟div:

render(){
返回(
<div>
<div className=“MessageContainer”>
<div className=“MessagesList”>
{this.renderMessages()}
</div>
<div style={{float:“left”,清除:“both”}
ref={(el)=>{this.messagesEnd=el;}}>
</div>
</div>
</div>
);
}

然后在组件更新时滚动到它(即添加新消息时状态更新):

scrollToBottom=()=>{
this.messagesEnd.scrollIntoView({behavior:“smooth”});
}
componentDidMount(){
这个.scrollToBottom();
}
componentDidUpdate(){
这个.scrollToBottom();
}

我在这里使用的是标准的Element.scrollIntoView方法

发表评论