鍍金池/ 問答/HTML/ 如何在react中設(shè)置scrollTop

如何在react中設(shè)置scrollTop

問題描述 無法設(shè)置scrollTop, 已經(jīng)嘗試了google前三頁的搜索結(jié)果。

<div className="chat-list" id="chatListDOM" ref={input => this.chatListDOM = input}>
                <a className="more-history">加載更多歷史消息</a>
                {
                  chatList.map(item => {
                    return myId === item.sendId
                      ?<MessageType.MeText id={item.id} name={item.sendId} datetime={format(item.time, 'YYYY-MM-DD HH:mm')} text={item.text} />
                      :<MessageType.OthersText id={item.id} name={other.name} datetime={format(item.time, 'YYYY-MM-DD HH:mm')} text={item.text} />
                  })
                }
              </div>
.right {
      width: 480px; height: 100%; border-left: 1px solid #e8e8e8; background-color: #f3f3f3;
      .header {
        border-bottom: 1px solid #e2e2e2;
        p {line-height: 32px;}
      }
      .chat-history-warp {
        width: 100%; height: 380px; overflow-y: scroll;
        .chat-list {
          margin: 14px; display: block;
          .more-history {
            display: block; margin-bottom: 10px; text-align: center; font-size: 12px; color: #777; cursor: pointer;
          }
        }
      }
      .chat-input-warp{
        width: 100%; height: 98px; border-top: 1px solid #e8e8e8; 
        textarea {
          display: block; width: 100%; height: 60px; padding: 10px 14px; overflow-x: hidden; overflow-y: auto;
          resize: none; outline: 0; background-color: #fff; border: 0; word-break: break-all; font-size: 13px;
          line-height: 17px; -webkit-appearance: none; background-color: #f3f3f3;
        }
        .input-bottom {
          display: flex; flex-direction: row-reverse; margin: 5px 20px;
          .ant-btn {height: 26px; background-color: #6088e6;}
        }
      }
    }
  setChatListScrollBottom () {
    console.log(this.chatListDOM)
    this.chatListDOM.scrollTop = this.chatListDOM.scrollHeight;
    this.chatListDOM.scrollTo(this.chatListDOM.scrollHeight,this.chatListDOM.scrollHeight)
    ReactDOM.findDOMNode(this.chatListDOM).scrollTop = this.chatListDOM.scrollHeight;
    ReactDOM.findDOMNode(this.chatListDOM).scrollTo(this.chatListDOM.scrollHeight,this.chatListDOM.scrollHeight)
    setTimeout(()=>{document.getElementById('chatListDOM').scrollTop = this.chatListDOM.scrollHeight}, 1000);
    setTimeout(()=>{document.getElementById('chatListDOM').scrollTo(this.chatListDOM.scrollHeight,this.chatListDOM.scrollHeight)}, 1000);

    console.log(this.chatListDOM.scrollTop, this.chatListDOM.scrollHeight);
    // document.body.scrollTop = this.refs.chatList.scrollHeight;
    // console.log(this.refs.chatList, this.refs.chatList && this.refs.chatList.scrollTop, document.body.scrollTop)
  }
回答
編輯回答
笑浮塵

問題已經(jīng)解決了,是因為scrollTop要設(shè)置到父元素上。

2018年3月1日 14:16