最近寫聊天的項(xiàng)目的時(shí)候,發(fā)現(xiàn)展示消息列表的滾動(dòng)條出現(xiàn)之后始終保持在底部,那好吧,那就讓他有新消息的時(shí)候自動(dòng)滾到底部來啊.折騰啊折騰啊終于好了
- 自己搜一下如何設(shè)置可以讓滾動(dòng)條保持在最底部
在單純的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="滾動(dòng)條, scrollbar, 頁面底部, 聊天窗口, " />
<meta name="description" content="" />
<title>將滾動(dòng)條(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">請(qǐng)點(diǎn)擊“插入一行”按鈕客们,插入最新信息玫鸟,當(dāng)出現(xiàn)滾動(dòng)條時(shí)萧恕,滾動(dòng)條將自動(dòng)保持在底部闺鲸。</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滾動(dòng)條在最底部
雖然搜到了方法,還是scrollTop = scrollHeight
但是react里面這些屬性是只讀的,無效,繼續(xù)下一條,巴拉巴拉翻了好幾條,五條有八條的方法是一樣的,后來上了個(gè)廁所回來發(fā)現(xiàn),這種東西搜索的時(shí)候還是不能靠中文網(wǎng)站
于是乎-
第二次搜索 :
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輕松設(shè)置