react中聊天窗口滚动条固定在底部

JavaScript 2019-11-05 3058 0
21:48:38

当我们打开一个聊天页面,希望的是展示最新的聊天内容,因此就有了固定聊天滚动条在底部的需求,这样我们进来就会看得到最新的消息。

react中聊天窗口滚动条固定在底部

具体实现:

使用ref属性

首先在需要固定滚动条的区域元素上使用ref属性来获取实例对象

  1. <div className="chat-message" ref={(el) => { this.messagesBottom = el }}></div>

 写方法

  1. scrollToBottom(){
  2.     if (this.messagesBottom) {
  3.         const scrollHeight = this.messagesBottom.scrollHeight;//实例div的实际高度
  4.         const height = this.messagesBottom.clientHeight;  //实例可见区域高度
  5.         const maxScrollTop = scrollHeight - height;
  6.         this.messagesBottom.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
  7.         }
  8.     }

最后

react生命周期钩子函数调用

 

完。

 

发表评论