react scroll to bottom

最近寫聊天的項目的時候,發現展現消息列表的滾動條出現以後始終保持在底部,那好吧,那就讓他有新消息的時候自動滾到底部來啊.折騰啊折騰啊終於好了javascript

  • 本身搜一下如何設置能夠讓滾動條保持在最底部 在單純的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裏面,並無那麼容易去修改元素的樣式,嘗試未果,想破了腦袋仍是百度一下html

  • 第一次搜索: react 保持div滾動條在最底部 雖然搜到了方法,仍是scrollTop = scrollHeight可是react裏面這些屬性是隻讀的,無效,繼續下一條,巴拉巴拉翻了好幾條,五條有八條的方法是同樣的,後來上了個廁所回來發現,這種東西搜索的時候仍是不能靠中文網站 因而乎java

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

    完美

  • 解決方法:bash

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輕鬆設置網站

之後搜東西不加中文了!

相關文章
相關標籤/搜索