How to scroll to bottom in react?

前端 未结 19 875
执笔经年
执笔经年 2020-11-28 18:27

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

19条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 18:54

    Thanks to @enlitement

    we should avoid using findDOMNode, we can use refs to keep track of the components

    render() {
      ...
    
      return (
        
    { this.messageList = div; }} > { messageListContent }
    ); } scrollToBottom() { const scrollHeight = this.messageList.scrollHeight; const height = this.messageList.clientHeight; const maxScrollTop = scrollHeight - height; this.messageList.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0; } componentDidUpdate() { this.scrollToBottom(); }

    reference:

    • https://facebook.github.io/react/docs/react-dom.html#finddomnode
    • https://www.pubnub.com/blog/2016-06-28-reactjs-chat-app-infinite-scroll-history-using-redux/

提交回复
热议问题