如何在反应中滚动到底部? [英] How to scroll to bottom in react?

查看:42
本文介绍了如何在反应中滚动到底部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想搭建一个聊天系统,在进入窗口和有新消息进来时自动滚动到底部.在React中如何自动滚动到容器底部?

解决方案

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

render() {返回 (<div><div className="MessageContainer" ><div className="MessagesList">{this.renderMessages()}

<div style={{ float:"left", clear: "both" }}ref={(el) =>{ this.messagesEnd = el;}}>

);}

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

scrollToBottom = () =>{this.messagesEnd.scrollIntoView({行为:平滑"});}componentDidMount() {this.scrollToBottom();}componentDidUpdate() {this.scrollToBottom();}

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

I want to build a chat system and automatically scroll to the bottom when entering the window and when new messages come in. How do you automatically scroll to the bottom of a container in React?

解决方案

As Tushar mentioned, you can keep a dummy div at the bottom of your chat:

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>
  );
}

and then scroll to it whenever your component is updated (i.e. state updated as new messages are added):

scrollToBottom = () => {
  this.messagesEnd.scrollIntoView({ behavior: "smooth" });
}

componentDidMount() {
  this.scrollToBottom();
}

componentDidUpdate() {
  this.scrollToBottom();
}

I'm using the standard Element.scrollIntoView method here.

这篇关于如何在反应中滚动到底部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆