react scroll to bottom

4,279 阅读2分钟

最近写聊天的项目的时候,发现展示消息列表的滚动条出现之后始终保持在底部,那好吧,那就让他有新消息的时候自动滚到底部来啊.折腾啊折腾啊终于好了

  • 自己搜一下如何设置可以让滚动条保持在最底部 在单纯的html文件里面是这么干的,让
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="keywords" content="滚动条, scrollbar, 页面底部, 聊天窗口, " />
    <meta name="description" content="" />
    <title>将滚动条(scrollbar)保持在最底部的方法 </title>
</head>
<body>
<div id="example">
    <div id="example_main"
        <script type="text/javascript">
            function add()
            {
                var now = new Date();
                var div = document.getElementById('scrolldIV');
                div.innerHTML = div.innerHTML + 'time_' + now.getTime() + '<br />';
                div.scrollTop = div.scrollHeight;
            }
        </script>
        <span class="notice">请点击“插入一行”按钮,插入最新信息,当出现滚动条时,滚动条将自动保持在底部。</span><br />

        <div id="scrolldIV" style="overflow:auto; height: 100px; width: 400px; border: 1px solid #999;">
        </div>
        <input type="button" value="插入一行" onclick="add();">
      
    </div>
</div>
</body>
</html>

然而放在react里面,并没有那么容易去修改元素的样式,尝试未果,想破了脑壳还是百度一下

  • 第一次搜索: react 保持div滚动条在最底部 虽然搜到了方法,还是scrollTop = scrollHeight但是react里面这些属性是只读的,无效,继续下一条,巴拉巴拉翻了好几条,五条有八条的方法是一样的,后来上了个厕所回来发现,这种东西搜索的时候还是不能靠中文网站 于是乎

  • 第二次搜索 : react scroll to bottom 成功

    完美

  • 解决方法:

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: "auto" });
}

componentDidMount() {
  this.scrollToBottom();
}

componentDidUpdate() {
  this.scrollToBottom();
}

使用scrollIntoView轻松设置

以后搜东西不加中文了!